Sub topic 15
Converting between strings and numbers
This chapter assumes you can run Python code, use print(), and read a basic try/except block. It also assumes you know that str, int, and float are distinct types.
Why conversion is explicit
Python does not guess when you mix text and numbers. "3" + 4 raises a TypeError, because + would have to choose between concatenation and addition. Text from input(), files, and web requests always arrives as str, so you convert it yourself.
Parsing strings into numbers
int() and float() accept a string and return a number. str() goes the other way.
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) + "!")int("3.5") fails because int() accepts only whole-number text. To parse decimal text into an integer, go through float() first. Be aware that int(float("3.5")) truncates toward zero and gives 3.
Both functions are more tolerant than you might expect:
- Surrounding whitespace is ignored, so
int(" 42\n")is42. - Underscores between digits are allowed, so
int("1_000")is1000. int()takes a second argument for the base, soint("ff", 16)is255andint("101", 2)is5.
Converting numbers into strings
Use str() when you need plain text. Use an f-string when you also want control over the layout, as the previous chapter showed.
count = 7
print("Items: " + str(count))
print(f"Items: {count}")Handling bad input
Any string that does not look like a number raises ValueError. Wrap the conversion at the point where untrusted text enters your program, and decide what a failure means there.
def read_int(text, default=None):
try:
return int(text)
except ValueError:
return default
print(read_int("42"))
print(read_int("4x2"))
print(read_int("3.5", default=0))This prints 42, None, and 0. Catch ValueError only. A bare except: would also hide unrelated bugs.
The conversion paths
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| `"5" + 1` | `TypeError` | `int("5") + 1` |
| `int("3.5")` | `ValueError` | `int(float("3.5"))` |
| `int("1,000")` | `ValueError` | `int("1,000".replace(",", ""))` |
| Comparing `"10" < "9"` | `True`, because strings compare character by character | Convert both to `int` first |
Exercise
What do int(" 12 "), int("12.0"), and int(float("12.9")) do? Say which ones succeed and give the values.
Show answer
int(" 12 ") succeeds and returns 12, because whitespace is ignored. int("12.0") raises ValueError, because int() does not accept decimal text. int(float("12.9")) succeeds and returns 12, because int() truncates toward zero.
Exercise
Write a function to_float(text) that returns the float for text, or None if the text cannot be parsed. What does to_float("2.5kg") return?
Show answer
def tofloat(text):
try:
return float(text)
except ValueError:
return None
`tofloat("2.5kg") returns None, because float("2.5kg")` raises ValueError and the function catches it.