Python convert string to int 6 examples

In this post:

  • Convert string to int
  • Convert string to float
  • Python Convert string to float(get the numbers before the decimal point)
  • Python Convert string to float(get the numbers after the decimal point)
  • Convert string mixed numbers and letters 11a to int
  • Convert string containing formatted number 11,111.00 to int

Convert string to int

The simplest conversion is when you are sure that your string contains a number which is an integer. In this case you can use:

num = "11"
print(int(num)) 

result:

11

Note:

If you have a string which contains decimal number like:

num = "11.02"
print(int(num)) 

You'll get error if you use int - instead of int use float:

'# ValueError: invalid literal for int() with base 10: '11.43'

If you have a string which contains letters and numbers like:

num = "11a"
print(int(num)) 

You'll get error:

'# ValueError: invalid literal for int() with base 10: '11a'

Convert string to float

Sometimes your string will contain number which is with decimal point. In order to avoid errors you need to use:

num = "10.55"
print(float(num))

result:

10.55

giving an integer to float is not causing error:

num = "10"
print(float(num))
10

Python Convert string to float(get the numbers before the decimal point)

If you want to convert string containing float to integer you can do it in two steps: first converting to float and then to int:

b = "12.43"
print(int(float(b)))

result:

12

Python Convert string to float(get the numbers after the decimal point)

There are two ways of getting the numbers after the decimal point while converting string to int. The first one is more accurate:

num = '17.58'
res = Decimal(num) % 1
print(res)

result:

0.58

The second one is less accurate:

num = '17.58'
frac, whole = math.modf(float(num))
print(frac)
print(whole)

result:

0.5799999999999983
17.0

Convert string mixed numbers and letters to int

Sometimes you will have extra numbers or other characters in your string in order to avoid errors you can replace the letters:

num = '11a'
pattern = re.compile(r"\w")
res = re.sub("[A-Za-z]+", "", num)
print(int(res)) 

result:

11

Convert string containing formatted number 11,111.00 to int

Sometimes the numbers that you will have will be formatted. You can easily workaround the format by:

num = "11,111.67"
res = re.sub(",", "", num)
print(float(res)) 

result:

11111.67