AppDividend
Latest Code Tutorials

How To Convert Python String to Int and Int to String

1

Python int() is a standard inbuilt function that converts the string to integer value. Python str() is an inbuilt function that converts int to string. The int() function with a string containing a number as an argument returns the number converted to an integer.

Just like the str() built-in function, Python also offers a handy built-in, which takes a String object as an argument and returns an integer object.  Python defines the type conversion functions to directly convert one data type to another data type, which is useful in day to day competitive programming.

Python int() is a standard built-in function to convert the string into an integer value.

Python str() is a standard built-in function to convert the integer to string value.

You call it with the string containing the number as the argument, and it returns the number converted to an integer.

How To Convert Python String to Int example

If you are looking for a solution to converting Python string to int and int to string then you will find your answer in this post. By the end of this tutorial, you’ll understand:

  1. Convert Python string to int.
  2. Convert Python str to int different base.
  3. Convert Python str to int with commas.

Python defines type conversion functions to directly convert one data type to another, which is useful in day to day and competitive programming.

This article is aimed at providing information about certain conversion functions.

We can use the type function to get the data type of any variable.

See the following example.

# app.py

amp = '123'
print(type(amp))

eli = 'The Computer Guy'
print(type(eli))

num = 1234
print(type(num))

ser = [1, 2, 4]
print(type(ser))

dict = {1: 'Android', 2: 'iOS', 3: 'Symbian'}
print(type(dict))

We have taken the different types of variables and printed them on the Python Console. See the following output.

How To Convert Python String to Int

Just like the str() built-in, Python also offers a handy built-in, which takes a String object as an argument and returns the corresponding integer object.

If you want to convert the number that is represented in a string to int, you have to use the int() function to do so. See the following example.

# app.py

amp = '123'
print(type(amp))

convertedInt = int(amp)
print(type(convertedInt))
print(convertedInt)

See the below output.

How To Convert Python String to Int and Int to String

We have converted the String to Integer in Python.

Integers are whole numbers. In other words, they have no fractional component. Two data types you can use to store an integer in Python are int and str.

These types offer flexibility for working with integers in different circumstances.

In this tutorial, you’ll learn how you can convert a Python string to an int. You’ll also learn how to convert an int to a string.

So, this is the same as python string to int.

#app.py

eleven = "11"
print(eleven)
# Converting string to number
millie = int(eleven)
print(millie)

See the output.

➜  pyt python3 app.py
11
11
➜  pyt

#Python str to int from different base

Strings can be transformed into numbers by using the int() and float() methods. If your string does not have decimal places, you will most probably want to convert it to an integer by utilizing the int() method.

If the string you want to convert into int belongs to a different number base other than base 10, then you can specify that base for that conversion.

But one thing, you need to keep in mind that the output integer is always in base 10. 

Another thing you need to remember is that a given base must be between 2 to 32.  See the following example.

# app.py

amp = '123'
print(type(amp))

convertedInt = int(amp)
print(type(convertedInt))
print(convertedInt)

convertedInt8 = int(amp, base=8)
print(type(convertedInt))
print(convertedInt)

convertedInt16 = int(amp, base=16)
print(type(convertedInt16))
print(convertedInt16)

convertedInt32 = int(amp, base=32)
print(type(convertedInt32))
print(convertedInt32)

See the below output.

Converting String to int from different base

While converting from string to int, you may get ValueError exception. The ValueError exception occurs if the string you want to convert does not represent any numbers. 

If you’re going to convert the hexadecimal number to an integer, then you did not have to pass the argument base=16 in the int() function.

It will raise the ValueError exception if there is any digit that does not belong to a decimal number system.

You should remember some of the special cases:

  1. The floating-point(an integer with a fractional part) as an argument will return the float rounded down to the nearest whole integer. For example: print(int(11.21)) will print 7. Also, print(int(“11.21”))  will result in the error since the string is an invalid argument to convert to an integer.

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '11.21'
  2. Also, any integer in words, if given as the argument, will return the same error as above: print(int(“eleven”))  will give an error as follows.

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: 'eleven'

#How to convert Python int to string example

Python str() is an inbuilt function that converts an integer to String.

See the following example.

# app.py

hexValue = 0x2f22
print(hexValue)
print(type(hexValue))
hexValue = str(hexValue)
print(hexValue)
print(type(hexValue))

See the output below.

Convert Python Int to String Tutorial

See another example of Int to String conversion in Python.

# app.py

digit = 1921
print(digit)
print(type(digit))
digit = str(digit)
print(digit)
print(type(digit))

Convert Python Int to String Tutorial Example

#Python decimal string to float number conversion

You may use a floating class for converting the decimal string to float number.

See the following example for a demonstration.

# app.py

eleven = '11.21'
hopper = 19.21

el = float(eleven) + hopper
print ("The value of el = ",el)

See the following output.

➜ pyt python3 app.py
The value of el = 30.42
➜ pyt

#Convert string numbers in a Python list to integers

If you intend to convert the string numbers contained in the python list, then one of the ways to convert those strings into an int is using a list comprehension.

A new list will be created where you may use the int in each iteration, as shown in the example below.

# app.py

str_list = ['11', '19', '21']
int_list = [int(a) for a in str_list]
print (int_list)

See the following output.

➜  pyt python3 app.py
[11, 19, 21]
➜  pyt

#Python str to int with commas

What about string numbers with commas like “11,000,000”. If you try to convert this string by using an int or float, it will generate the error because of the commas.

The solution to the above error is by importing the locale.

import locale

Now, you can use the USA locale setting like the following.

locale.setlocale( locale.LC_ALL, "en_US.UTF-8")

However, this may cause problems with different locations.

So, one other solution is to replace the comma by nothing. For example, see the code below.

# app.py

elevenmillion = '11,000,000'
eleven = int(elevenmillion.replace(',',''))

print ("The integer value", eleven)

See the following output.

➜  pyt python3 app.py
The integer value 11000000
➜  pyt

Conclusion

Strings can be converted to numbers using the int() and float() functions. So this is how you can convert Python string to a number.

If the string does not have decimal places, you’ll most likely want to convert it to an integer by using the int() method.

The str() function is used to convert the integer to String in Python.

The ord() function is used to convert the character to an integer.

The hex() function is used to convert an integer to a hexadecimal string.

The oct() function is to convert an integer to the octal string.

Finally, How To Convert Python String to Int and Int to String Tutorial With Example is over.

Recommended Posts

Python float() example

Python pow() example

Python datatypes example

Python operators example

Python sum()

1 Comment
  1. Hiral says

    Thanks for posting, this article was very helpful when converting string to int and vice versa. I came across a similar post though it was certainly not quite as thorough as this!

    Thanks again,

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.