note.nkmk.me

Convert a string to int and float in Python

Posted: 2020-10-19 / Tags: Python, String

In Python, you can convert a string str to an integer int and a floating point number float with int() and float()

This post describes the following contents.

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

Use str() to convert an integer or floating point number to a string.

Sponsored Link

Convert a string to an integer: int()

int() converts a string of numbers to an integer int.

print(int('100'))
print(type(int('100')))
# 100
# <class 'int'>

A string containing . or , causes an error.

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

# print(int('10,000'))
# ValueError: invalid literal for int() with base 10: '10,000'

A comma-separated string can be converted by deleting , with replace () (replace with empty string '').

print(int('10,000'.replace(',', '')))
# 10000

See the following post for replace().

Convert a string to a floating point number: float()

float() converts a string of numbers to a floating point number float.

print(float('1.23'))
print(type(float('1.23')))
# 1.23
# <class 'float'>

A string with the integer part omitted can be converted.

print(float('.23'))
# 0.23

A string representing an integer is also converted to a floating point number float.

print(float('100'))
print(type(float('100')))
# 100.0
# <class 'float'>
Sponsored Link

Convert a string of binary, octal, and hexadecimal notation to int

If you pass a base number to the second argument of int(), a string is treated as binary, octal and hexadecimal.

print(int('100', 2))
print(int('100', 8))
print(int('100', 16))
# 4
# 64
# 256

If omitted, it is regarded as decimal like the previous examples.

print(int('100', 10))
print(int('100'))
# 100
# 100

If the base is 0, it is converted based on the prefix of the string (0b, 0o, 0x or 0B, 0O, 0X).

print(int('0b100', 0))
print(int('0o100', 0))
print(int('0x100', 0))
# 4
# 64
# 256

Prefixes and hexadecimal alphabets may be written in either upper or lower case.

print(int('FF', 16))
print(int('ff', 16))
# 255
# 255

print(int('0xFF', 0))
print(int('0XFF', 0))
print(int('0xff', 0))
print(int('0Xff', 0))
# 255
# 255
# 255
# 255

Convert a string of exponential notation to float

A string of exponential notation can be converted into a float with float().

print(float('1.23e-4'))
print(type(float('1.23e-4')))
# 0.000123
# <class 'float'>

print(float('1.23e4'))
print(type(float('1.23e4')))
# 12300.0
# <class 'float'>

You can use E instead of e.

print(float('1.23E-4'))
# 0.000123
Sponsored Link
Share

Related Categories

Related Posts