PythonMastery

How do I convert a string to a number in Python?

int('42') and float('3.5') convert text to numbers. int('3.5') fails, so go through float() first. Wrap input from users in try/except ValueError and ask again.

int() for whole numbers, float() for anything with a decimal point.

python
quantity = int("3")
price = float("4.75")

print(quantity * price)
output
14.25

Surrounding spaces and a trailing newline are fine, which helps with lines read from a file or typed by a user:

python
print(int("  42\n") + 1)
output
43

What fails, and what to do about it

int() is strict. It refuses anything that isn't a plain whole number:

python
for text in ["3.5", "1,250", "£20", ""]:
    try:
        print(int(text))
    except ValueError as e:
        print(e)
output
invalid literal for int() with base 10: '3.5'
invalid literal for int() with base 10: '1,250'
invalid literal for int() with base 10: '£20'
invalid literal for int() with base 10: ''

Each has its own fix:

python
print(int(float("3.5")))                # 3: float first, then drop the decimals
print(round(float("3.5")))              # 4: or round it
print(int("1,250".replace(",", "")))    # 1250: remove thousands separators
print(float("£20".lstrip("£")))         # 20.0: strip the currency symbol
output
3
4
1250
20.0

round() uses banker's rounding, so round(2.5) is 2, not 3: halves go to the even neighbour.

Numbers from a user

People type things you don't expect. Keep asking until the answer converts:

python
def ask_age(answers):
    for text in answers:              # stands in for input() so this runs as-is
        try:
            return int(text)
        except ValueError:
            print(f"{text!r} isn't a whole number, try again")

print(ask_age(["twenty", "20.5", "20"]))
output
'twenty' isn't a whole number, try again
'20.5' isn't a whole number, try again
20

In a real program, the loop is while True: with text = input("Age: ").

And back again

str(14.25) turns a number into text. For joining text and numbers, an f-string does the conversion for you: f"Total: {total}". Writing "Total: " + total raises TypeError: can only concatenate str.

If the numbers are money, look at decimal.Decimal("4.75") instead of float: floats can't store most decimal fractions exactly, which is why 0.1 + 0.2 isn't 0.3.

Go deeper: Numbers in Depth: Integers, Floats, and the math Module, ValueError: invalid literal for int() with base 10, TypeError: unsupported operand type(s) for +: 'int' and 'str'

More short answers

all questions