Python string to number
last modified November 19, 2026 Python 3.15
In this article we show how to convert strings to numbers in Python.
Data read from files, command lines, forms, and network messages arrives as
text. Before we can calculate with it, we convert it with the
int and float functions, or with
Decimal and Fraction when we need exact results.
The conversion fails when the text is not a valid number, so handling invalid
input is a large part of the job. The opposite direction is covered in
Python int to string.
int and float
The int function converts a string to an integer and
float converts it to a floating-point number.
#!/usr/bin/python
print(int('42') + 1)
print(float('3.14') * 2)
print(int(' -17\n'))
print(int('1_000_000'))
print(float('1e3'), float('.5'), float('-2.'))
Both functions ignore whitespace around the number and accept a sign and underscores between digits, as in Python literals. A float string can use the exponent notation and may omit the digits before or after the decimal point.
$ python convert_basic.py 43 6.28 -17 1000000 1000.0 0.5 -2.0
Invalid input
A string that is not a valid number raises a ValueError.
#!/usr/bin/python
inputs = ['3.0', '1,5', '', 'twelve', '0x1f', '1 000']
for s in inputs:
try:
print(int(s))
except ValueError as e:
print(e)
The int function rejects decimal points, commas, empty strings,
and inner spaces. A hexadecimal literal such as 0x1f needs an
explicit base, shown later. The error message includes the offending string,
which helps when reporting bad input to the user.
$ python invalid.py invalid literal for int() with base 10: '3.0' invalid literal for int() with base 10: '1,5' invalid literal for int() with base 10: '' invalid literal for int() with base 10: 'twelve' invalid literal for int() with base 10: '0x1f' invalid literal for int() with base 10: '1 000'
Safe conversion
To convert values that may be invalid without stopping the program, we wrap the conversion in a function that catches the error.
#!/usr/bin/python
def to_int(s, default=None):
try:
return int(s)
except (ValueError, TypeError):
return default
def to_number(s):
try:
return int(s)
except ValueError:
return float(s)
print([to_int(s) for s in ['7', 'n/a', None, ' 12 ']])
print([to_int(s, 0) for s in ['7', 'n/a', None]])
print([to_number(s) for s in ['7', '7.0', '7e2']])
The to_int function returns a default value for invalid input.
It also catches TypeError, raised when the value is
None, as happens with missing fields. The
to_number function tries an integer first and falls back to a
float; if both fail, the ValueError from float
reaches the caller. Asking for forgiveness like this is the usual Python
style, and it is more reliable than checking the string in advance.
$ python safe_convert.py [7, None, None, 12] [7, 0, 0] [7, 7.0, 700.0]
isdecimal, isdigit, and isnumeric
Strings have three methods that check for digits. They differ in which
Unicode characters they accept, and none of them guarantees that
int succeeds.
#!/usr/bin/python
samples = ['42', '-42', '3.5', '²', '٣', '½', 'Ⅻ']
print(f'{"":5} {"decimal":8} {"digit":8} {"numeric":8} int')
for s in samples:
try:
value = int(s)
except ValueError:
value = '-'
print(f'{s:5} {s.isdecimal()!s:8} {s.isdigit()!s:8} '
f'{s.isnumeric()!s:8} {value}')
All three return False for a sign or a decimal point, so they
reject -42 and 3.5, which are valid numbers. The
isdigit method accepts the superscript ², but
int does not. The isnumeric method also accepts
fractions, Roman numerals, and Chinese numerals. Only
isdecimal matches what int accepts, which includes
the Arabic-Indic digit three.
$ python digit_methods.py
decimal digit numeric int
42 True True True 42
-42 False False False -42
3.5 False False False -
² False True True -
٣ True True True 3
½ False False True -
Ⅻ False False True -
Unicode digits
The int and float functions accept the decimal
digits of all scripts, not only the ASCII digits 0 to 9.
#!/usr/bin/python
import unicodedata
print(int('٤٢'), int('४२'), int('42'))
print(float('٣.٥'))
for c in '٤४4²':
print(c, unicodedata.name(c), unicodedata.decimal(c, None),
unicodedata.digit(c, None))
def ascii_int(s):
s = s.strip()
if not (s.isascii() and s.lstrip('+-').isdecimal()):
raise ValueError(f'not an ASCII integer: {s!r}')
return int(s)
print(ascii_int(' -42 '))
try:
ascii_int('٤٢')
except ValueError as e:
print(e)
Arabic-Indic, Devanagari, and fullwidth digits all convert to 42. The
unicodedata.decimal function returns the value of a decimal
digit, while digit also knows the superscripts. When a field must
contain ASCII digits only, for example an account number, we check it with
isascii and isdecimal, as in the
ascii_int function.
$ python unicode_digits.py 42 42 42 3.5 ٤ ARABIC-INDIC DIGIT FOUR 4 4 ४ DEVANAGARI DIGIT FOUR 4 4 4 FULLWIDTH DIGIT FOUR 4 4 ² SUPERSCRIPT TWO None 2 -42 not an ASCII integer: '٤٢'
Other bases
The second argument of int is the base of the number, from 2 to
36.
#!/usr/bin/python
def parse_color(text):
text = text.removeprefix('#')
if len(text) == 3:
text = ''.join(c * 2 for c in text)
return tuple(int(text[i:i + 2], 16) for i in (0, 2, 4))
for color in ['#1e90ff', '#FFF', '000080']:
print(color, parse_color(color))
print(int('0755', 8), int('11111111', 2), int('z', 36))
A web color consists of three hexadecimal pairs for red, green, and blue. The
parse_color function slices the pairs and converts each with base
16; the short form #FFF is expanded by doubling each digit. The
last line converts an octal file mode, a binary byte, and a letter in base 36.
Base 0, which reads the base from a 0x, 0o, or
0b prefix, and the limit on the length of integer strings are
shown in Python int to string.
$ python hex_color.py #1e90ff (30, 144, 255) #FFF (255, 255, 255) 000080 (0, 0, 128) 493 255 35
Special float values
The float function accepts some strings that are not ordinary
numbers.
#!/usr/bin/python
import math
for s in ['nan', 'inf', '-Infinity', '1e400', '1e-400']:
print(f'{s:10} {float(s)}')
def to_finite(s):
x = float(s)
if not math.isfinite(x):
raise ValueError(f'not a finite number: {s!r}')
return x
for s in ['2.5', 'NaN', '1e400']:
try:
print(to_finite(s))
except ValueError as e:
print(e)
The strings nan, inf, and infinity, in
any case and with an optional sign, give special values. A number too large
for a float becomes infinity and a number too small becomes zero, without an
error. When such values are not acceptable input, we check the result with
math.isfinite.
$ python float_special.py nan nan inf inf -Infinity -inf 1e400 inf 1e-400 0.0 2.5 not a finite number: 'NaN' not a finite number: '1e400'
Exact decimal numbers
Floats are binary numbers and cannot store most decimal fractions exactly.
The Decimal and Fraction types accept strings and
keep their exact value.
#!/usr/bin/python
from decimal import Decimal
from fractions import Fraction
a, b = '0.1', '0.2'
print(float(a) + float(b))
print(Decimal(a) + Decimal(b))
prices = ['0.10', '0.20', '0.30']
print(sum(Decimal(p) for p in prices))
print(Decimal('19.990'), Decimal('1e3'))
print(Fraction('3/4') + Fraction('0.5'))
The float sum of 0.1 and 0.2 has a rounding error, the Decimal
sum does not. A Decimal created from a string also keeps the
number of decimal places, so the sum of the prices is 0.60. The
Fraction type accepts strings such as 3/4. Money
calculations with decimals are covered in
Python decimal.
$ python exact.py 0.30000000000000004 0.3 0.60 19.990 1E+3 5/4
Locale-formatted numbers
Numbers written for people use thousands separators, and many languages use
a comma as the decimal point. The locale module parses numbers by
the rules of a locale.
#!/usr/bin/python
import locale
locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
print(locale.atof('1,234,567.5'), locale.atoi('1,024'))
locale.setlocale(locale.LC_NUMERIC, 'sk_SK.UTF-8')
text = locale.format_string('%.2f', 1234567.5, grouping=True)
print(text, ascii(text))
print(locale.atof(text))
print(float('1,234,567.5'.replace(',', '')))
In the US locale, locale.atof removes the commas. In the Slovak
locale, the decimal point is a comma and thousands are separated by a narrow
no-break space, U+202F, as the ascii function shows. Text typed
by people often uses an ordinary space instead and then fails to parse. For a
known format, removing the separators with replace is simpler.
The program needs the en_US.UTF-8 and sk_SK.UTF-8
locales installed on the system.
$ python locale_numbers.py 1234567.5 1024 1 234 567,50 '1\u202f234\u202f567,50' 1234567.5 1234567.5
Numbers in text
To pull numbers out of a sentence, we search for them with a regular expression and convert the matches.
#!/usr/bin/python
import re
text = ('The flight took 2.5 hours, cost $1,299 and covered '
'-3 time zones and 4100 km.')
print(re.findall(r'\d+', text))
NUMBER = re.compile(r'-?\d{1,3}(?:,\d{3})+(?:\.\d+)?|-?\d+(?:\.\d+)?')
numbers = [float(m.replace(',', '')) for m in NUMBER.findall(text)]
print(numbers)
The simple pattern \d+ splits 2.5 and
1,299 into pieces and loses the minus sign. The second pattern
has two alternatives: a number with comma-separated thousands, and a plain
number. Both allow a sign and a decimal part. We remove the commas before
converting the matches to floats.
$ python extract_numbers.py ['2', '5', '1', '299', '3', '4100'] [2.5, 1299.0, -3.0, 4100.0]
Reading numbers from a file
In the last example we read temperatures from a file. Some lines contain invalid values.
# station temperature Bratislava 12.5 Kosice 9.75 Zilina n/a Presov 8,5 Nitra 14 Poprad -2.25 Trnava 1e400
The program reports the invalid lines and computes statistics from the valid ones.
#!/usr/bin/python
import math
def parse(line):
name, _, value = line.partition(' ')
try:
temp = float(value)
except ValueError:
return name, None, f'not a number: {value!r}'
if not math.isfinite(temp):
return name, None, f'out of range: {value!r}'
return name, temp, None
temps = {}
with open('readings.txt') as f:
for no, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith('#'):
continue
name, temp, error = parse(line)
if error:
print(f'line {no}: {name}: {error}')
else:
temps[name] = temp
print(f'{len(temps)} valid readings')
print(f'average {sum(temps.values()) / len(temps):.2f}')
print(f'coldest {min(temps, key=temps.get)}')
The parse function splits the line at the first space and
converts the value. Instead of raising an exception, it returns an error
message, so the main loop can report the line number. The value
8,5 uses a decimal comma and is rejected, and
1e400 is caught by the isfinite check.
$ python readings.py line 4: Zilina: not a number: 'n/a' line 5: Presov: not a number: '8,5' line 8: Trnava: out of range: '1e400' 4 valid readings average 8.50 coldest Poprad
Source
str.isdecimal – Python documentation
In this article we have converted strings to numbers in Python. See also Python int to string, Python int function, Python float function, and Python decimal.
Author
List all Python tutorials.