Sub topic 15
Converting between strings and numbers
This chapter assumes you know that str, int, and float are different types. It also assumes you can use f-strings for basic output and read a traceback. Here you will learn what the parsing functions accept, how they fail, and how to turn numbers back into text on purpose.
Why conversion is explicit
Python does not convert between text and numbers on its own. "5" + 1 raises TypeError, and "5" * 3 is the string "555". Data from input(), files, command-line arguments, and web requests arrives as str. You must convert it before doing arithmetic.
print(int("42") + 1)
print(float("3.5"))
try:
int("3.5")
except ValueError as e:
print("ValueError:", e)
print(int(float("3.5")))
print(str(42) + "!")The output is 43, 3.5, a ValueError message, 3, and 42!. The constructors int(), float(), and str() each build a new object from their argument. They never change the original.
What int() accepts
int(text) takes a string holding a whole number in base 10. It ignores leading and trailing whitespace, accepts an optional + or -, and allows single underscores between digits.
| Call | Result |
|---|---|
| `int("42")` | `42` |
| `int(" 42\n")` | `42` |
| `int("-7")` | `-7` |
| `int("1_000")` | `1000` |
| `int("3.5")` | `ValueError` |
| `int("1,234")` | `ValueError` |
| `int("")` | `ValueError` |
| `int("0x1f")` | `ValueError` |
The whitespace rule helps with input() and file lines, which often end in a newline. The comma rule matters for user input. Strip thousands separators yourself with text.replace(",", "") before parsing, and only when you know the format.
Other bases
The second argument sets the base, from 2 to 36. With base 0, Python reads the prefix and picks the base like a source literal.
print(int("ff", 16))
print(int("0x1f", 16))
print(int("0b101", 0))
print(int("777", 8))
print(bin(10), hex(255), oct(8))
print(format(255, "x"), format(255, "08b"))This prints 255, 31, 5, 511, then 0b1010 0xff 0o10, then ff 11111111. The base argument works only when the first argument is a string. int(255, 16) raises TypeError.
What float() accepts
float(text) accepts decimal points, exponents, and the same whitespace and sign rules. It also accepts the special words inf, -inf, and nan, in any letter case.
print(float("1e3"))
print(float("-.5"))
print(float(" 2.5 "))
print(float("inf"))
print(float("NaN"))This prints 1000.0, -0.5, 2.5, inf, and nan. A user who types nan into a form is not making a typo as far as Python is concerned, so check for it. nan is not equal to anything, including itself, and it spreads through arithmetic. math.isfinite rejects both nan and the infinities.
import math
def read_price(text):
value = float(text)
if not math.isfinite(value):
raise ValueError(f"not a finite number: {text!r}")
return value
for t in ["12.5", "nan", "abc"]:
try:
print(read_price(t))
except ValueError as e:
print("ValueError:", e)The three results are 12.5, ValueError: not a finite number: 'nan', and ValueError: could not convert string to float: 'abc'.
Handling failures
Bad text raises ValueError. A wrong type, such as None, raises TypeError. Catch the narrowest exception that fits the situation, and keep the try block small so other bugs are not hidden.
def parse_int(text, default=None):
try:
return int(text)
except (ValueError, TypeError):
return default
print(parse_int("42"))
print(parse_int("4x2"))
print(parse_int("", 0))
print(parse_int(None, -1))This prints 42, None, 0, and -1.
Converting floats to ints
int() applied to a float truncates toward zero, so int(3.9) is 3 and int(-3.9) is -3. To get another behavior, choose it explicitly:
round(x)rounds to the nearest integer, and exact halves go to the even neighbor.round(2.5)is2andround(3.5)is4.math.floor(x)rounds toward negative infinity.math.ceil(x)rounds toward positive infinity.
Converting a big integer string through float can lose digits, because a float keeps only about 15 to 17 significant digits.
big = "12345678901234567890"
print(int(big))
print(int(float(big)))The first line prints the exact value. The second prints 12345678901234567168. If the text is an integer, parse it with int() directly and skip the float.
Parsing exact decimals
Parsing "0.1" with float() produces the nearest binary float, which is not exactly 0.1. For money and other values where decimal digits matter, parse the string straight into Decimal.
from decimal import Decimal, InvalidOperation
price = Decimal("19.99")
print(price * 3)
print(Decimal(" 1.50 "))
try:
Decimal("abc")
except InvalidOperation:
print("InvalidOperation")This prints 59.97, 1.50, and InvalidOperation. Decimal keeps the trailing zero you typed. Notice that bad text raises InvalidOperation here, not ValueError. Pass strings to Decimal, not floats. Decimal(0.1) faithfully copies the float's binary error.
Converting numbers to strings
str(x) gives a readable form. repr(x) gives an unambiguous form that is meant for debugging. For floats, both use the shortest text that reads back as the same float.
print(str(3.0), str(1e16), str(0.1 + 0.2))
print(float(repr(0.1 + 0.2)) == 0.1 + 0.2)
print(str(True), str(None))This prints 3.0 1e+16 0.30000000000000004, then True, then True None. So str(3.0) keeps the .0, and large floats switch to exponent notation.
When the text is meant for people, use an f-string with a format specifier so you control the digits.
total = 1234.5
print(f"{total:,.2f}")
print(f"{total:.0f}")
print(f"{7:03d}")
print(f"{0.256:.1%}")This prints 1,234.50, 1234 (the .0f form rounds halves to even, like round), 007, and 25.6%. A formatted string is text. Don't parse it back for math. Keep the number, and format only at the edge of your program.
Limits on very large integers
Since Python 3.11, converting an int to or from a decimal string is limited to 4300 digits by default. int("9" * 5000) raises ValueError, and so does str(10**5000). The limit defends against denial-of-service attacks, because these conversions take time that grows with the square of the length. Power-of-two bases such as 2, 8, 16, and 32 are not limited. If you really need longer numbers, sys.set_int_max_str_digits() changes the limit. Raise it only for trusted input.
Common mistakes
- Treating
input()as a number.age = input()thenage + 1raisesTypeError. Writeage = int(input()). - Using
int("3.5")and expecting truncation. It fails, so go throughfloatonly when a float value is acceptable. - Concatenating without
str(). Use an f-string, such asf"Total: {n}", instead of"Total: " + n. - Trusting
float()output as finite. Checkmath.isfinitefor outside data. - Using floats for currency. Parse with
Decimalfrom the start.
Exercise
Write a function to_cents(text) that takes a price string like "19.99" or " 5 " and returns the integer number of cents (1999 or 500). It must not use float arithmetic. Which type should do the parsing, and what does to_cents("0.1") return?
Show answer
Parse with Decimal, then scale and convert to int. from decimal import Decimal def tocents(text): return int(Decimal(text) * 100) print(tocents("19.99")) print(tocents(" 5 ")) print(tocents("0.1")) The output is 1999, 500, and 10. Decimal("0.1") is exact, so multiplying by 100 gives exactly 10. A float would risk values like 1998.9999999999998 that int() truncates to 1998. Invalid text raises decimal.InvalidOperation.
Exercise
Predict the result of each call: int(" -12 "), int("12.0"), int(float("12.9")), int("101", 2), and float("1_0.5").
Show answer
int(" -12 ") is -12, because whitespace and a sign are allowed. int("12.0") raises ValueError, because int() on a string accepts only whole-number text. int(float("12.9")) is 12, because int() truncates the float. int("101", 2) is 5. float("1_0.5") is 10.5, because underscores between digits are allowed.