How to Convert String to Integer or number in Python

Python is a High Level Programming language which was introduced in 1991. It amazing features make it significant from other programming languages. In certain conditions, you need to undergo several data type conversions i.e. int to string, string to int etc. In previous article, the conversion, int to string was discussed. You can access it from the link given below;

How to Convert Int to String in Python

Here we will discuss how to convert string to int in python. This conversion has great importance as it is necessary in many conditions. For this purpose there is integer function "int()" in Python. Following tutorial will help you to understand how to convert string to int or number in Python.

ADVERTISEMENT

String to Int in Python

You can convert string to integer in three easy steps. These steps are mentioned below;

  1. Launch your Python editor.
  2. Type int(string).
  3. Press Enter.

Consequently, this will run the command and convert string to integer.

Examples to Convert String to Integer

Here are some examples for your better understanding. Moreover, you can learn this conversion easily with the help of following examples.

ADVERTISEMENT

Example 1

In the following example string is converted to  integer by using int() function.

"number = '123' # string data

# print the type

ADVERTISEMENT

print('number type', type(number))

# convert using int()

number = int(number)

# print the type again

print('Now, type of number ', type(number))"

Output

number type  <class 'str'>
Now, number type <class 'int'>

Example 2

str_a = '50'
b = 10
c = int(str_a) + b
print ("The value of c = ",c) "

Conclusion

I hope that these examples are enough for you to understand how to convert string to integer or number in Python. Moreover, you can learn the correct use of int() function. These data types can help you a lot while programming. So, if you cannot still understand, feel free to ask in comments about errors.

No posts to display