Convert a Python String to int and float

Infographic: Converting Python String to Integer and Float - A visual guide illustrating how to convert Python strings to integer and floating-point numbers using int() and float() functions.

How to convert Python string to an int and float

In certain scenarios, you may need to convert a string to an integer or float for performing certain operations in Python.

If you try doing some action with a “string number” like addition, or subtraction, it will generate an error as shown below.

The code that will produce an error:

str_a = ’50’

b = 10

c = str_a + b

print (c)

The output:

Python string to int

You may use the Python int and float functions for converting a string to an integer and float numbers before doing any operation, as shown in the examples below.

Using int() function for converting a string into an integer

Using the same code as in the above example, except converting the string value into an integer by using int. See the code and output:

The code:

str_a = '50'

b = 10

c = int(str_a) + b

print ("The value of c = ",c)

Output:

int

The output is the value of c, which is the sum of the variables str_a and b.

Converting a decimal string into float number

You may use the float class for converting a decimal string to a float number. See the following example for demonstration:

The code of using float for converting a string:

#A demo of string to float



str_a = '50.85'

b = 10.33

c = float(str_a) + b

print ("The value of c = ",c)

Result:

Python string to float

Note: if you try using the int here, it will generate an error.

Converting string numbers in a Python list to integers

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

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

The code:

#A demo of string to int in a list

str_lst = ['1', '2', '3']



int_lst = [int(x) for x in str_lst]



print (int_lst)

Output:

list string to int

The output is a new list with strings converted into integers.

Converting decimal list into float for list items

Similarly, you may use the float instead of int for converting a list containing decimal number strings. See a demonstration below:

The code for converting list items to float:

#A demo of string to float in a list

str_lst = ['10.505', '2.3', '3.99']



float_lst = [float(x) for x in str_lst]



print (float_lst)

Output:

list string to float

An example of converting a string to int with commas

Well, what about string numbers with commas like “5,000,000”. If you try to convert this by using int or float, it will generate an error.

The solution to this can be importing locale:

import locale

and using the local setting like for the USA:

locale.setlocale( locale.LC_ALL, ‘en_US.UTF-8’ )

However, this may cause problems with different locations. One other solution is to replace the comma with nothing i.e. ” and then use the int, as shown in the example below:

The code:

str_a = '5,123,000'

int_b = int(str_a.replace(',',''))



print ("The integer value",int_b)

Result:

string to int comma

In the output, you can see a flat integer value. The same can be applied to converting a string to float.

The example of using the base argument for string to int

As such, you may also use the Python int function as follows:

class int(x, base=10)

That means you may provide base value for conversion as well. In the example below, I used various base values in the int function for the string to int conversion:

base36_1 = int('a', 36)
base36_2 = int('z', 36)
base36_3 = int('1', 36)
base36_4 = int('10', 36)

print(base36_1)
print(base36_2)
print(base36_3)
print(base36_4)

The output:

10
35
1
36

An example of base 16

The example below uses the base 16 value in the int() function:

base_16_1 = int('1', 16)
base_16_2 = int('A', 16)
base_16_3 = int('F', 16)
base_16_4 = int('10', 16)

print(base_16_1)
print(base_16_2)
print(base_16_3)
print(base_16_4)

The output:

1
10
15
16

Similarly, you may convert to binary and octal as well. To learn more about this, go to int() function tutorial.

An example of string to integer for leap years

The input entered by the user in Python program is taken as a string. In the following example, a user is asked to enter a year. After entering the value, the program tells if the entered year is a leap year or not.

For that, the entered value is first converted to int and then leap year formula is used to establish if it is a leap year or not.

#A Demo of parse Int for leap year
try:
Y = int(input("Enter a Year? "))

except ValueError:
print ("You may only enter digits in '2000' format!")
else:
leap_or_not = Y%4 == 0
if leap_or_not:
print ("Leap year")
else:
print ("Not a leap year")

The output:

string to integer

You see, the entered string is converted upfront to an integer and then used for calculation.

Note: Leap year has two other conditions:

  • (i) Year is not divisible by 100. For example, 1900 is not a leap year, although it can be divided by 4.
  • (ii)Year can be divided by 400 is a leap year. For example, 2000 is a leap year as it can be divided by 400 (though it can be divided by 100 as well).
  • (iii)You need to incorporate these two conditions as well in the above code by using if..else if ladder etc.

How to convert int to string?

In case you require converting the integers to string, you may use the str() function of Python. The str() function takes an object that can be an int, float, double etc.

See this simple example of converting an int type variable to a string and then this variable is used with a string variable for concatenation:

#Example of int to string

a_string = "str function for int to string"
a_num = 456

print (a_string + str(a_num))

The output:

str function for int to string456

If int variable was used without the str() function in the above example, a TypeError error should have been produced.

You may learn more about the str() function for converting int to strings.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!