Skip to main content
Python Convert a string to a number

Python Convert a string to a number

This python tutorial helps to convert a string into a number. We can convert string str to an integer int and a floating-point number float with int() and float().

We’ll cover the following topics in this python article:

  • Convert a string to an integer using int() method
  • Convert a string to a floating point number using float() method
  • Convert a string of binary, octal, and hexadecimal using int() method
  • Convert a string of exponential string to number using float() method

Convert a String to an Integer using int()

The int() method can be used to converts a string of numbers to an integer int.

print(int('12'))
print(type(int('12')))

Output:

12

Convert a String to an float number using float()

The float() method can be used to converts a string of numbers to a floating-point number.

print(float('12.45'))
print(type(float('12.45')))

Output:

12.45

Convert a Binary, Octal to an float number using float()

The int() method can be used to converts a string binary, octal, and hexadecimal into integre, we need to pass second argument as a base number.

Output:

4
64
256

Convert an exponential notation number using float()

The float() method can be used to convert an exponential string into a float number.

print(float('1.13e-4'))

Output:

0.000113

Leave a Reply

Your email address will not be published. Required fields are marked *