Why this matters
Data arrives as text: from input(), files, command-line arguments, network requests. Your program needs numbers, booleans and other types to compute with, and then text again to print results. Converting correctly, and knowing which conversions fail or silently lose information, is everyday work. This lesson also introduces repr, the tool that shows you what a value really is when printing it is not enough.
Conversion means making a new object
Python never changes the type of an existing object. "Converting" means calling a type to build a new object from an old one:
text = "42"
number = int(text)
print(text, type(text).__name__)
print(number, type(number).__name__)
42 str
42 int
text still refers to the string. int(text) read its characters and produced a separate int object. The types int, float, str and bool are callable, and calling one is how you construct values of that type.
To int
print(int("42"))
print(int(" -7\n")) # whitespace around is ignored
print(int("1_000")) # underscores between digits are allowed
print(int(3.99)) # float -> int truncates toward zero
print(int(-3.99))
print(int(True))
42
-7
1000
3
-3
1
int() of a string is strict: int("3.5"), int("12abc") and int("") all raise ValueError. That strictness is a feature: bad input fails loudly rather than becoming a wrong number.
Other bases
The second argument to int is the base the text is written in:
print(int("1010", 2)) # binary
print(int("ff", 16)) # hexadecimal, case does not matter
print(int("17", 8)) # octal
print(int("0x1F", 16)) # a 0x prefix is accepted when it matches the base
print(int("0b101", 0)) # base 0: read the prefix to decide
10
255
15
31
5
In base 16 the digits a-f mean 10-15. Bases from 2 to 36 are allowed. The reverse conversion (int to binary or hex text) uses bin(), hex() and oct(), covered with bitwise operators in the next module.
To float
print(float("3.14"))
print(float(" 2 "))
print(float("1e-3"))
print(float(7))
print(float("inf"), float("nan"))
3.14
2.0
0.001
7.0
inf nan
float() accepts anything that looks like a decimal or scientific-notation number. Converting a large int to float may lose precision, since a float has only 53 bits of mantissa: float(2**53 + 1) is 9007199254740992.0, which is 2**53, off by one.
To str
str(x) gives the "informal", human-readable text for a value. It is what print uses:
print(str(42) + "!")
print(str(3.0))
print(str(None))
print(str(True))
42!
3.0
None
True
Converting to str never fails for built-in types. You need it when joining with +, because "Age: " + 36 is a TypeError.
To bool: truthiness
bool(x) asks "is x considered true?". The rule for built-in types: zero and empty things are false, everything else is true.
| False | True |
|---|---|
False, None | True |
0, 0.0 | any other number, e.g. -1, 0.001 |
"" (empty string) | any non-empty string, even "False", "0", " " |
empty containers [], {} | non-empty containers |
print(bool("False"))
print(bool(""))
True
False
bool("False") is True because the string is non-empty; bool does not interpret the words. To turn user answers into booleans, compare text: answer == "yes". This "truthiness" is what if and while use, which the next module explores.
str versus repr
Every object has two text forms:
str(x): readable, for end users.printuses it.repr(x): unambiguous, for programmers. The REPL uses it to echo values. For built-in types it usually looks like the Python literal you would type to recreate the value.
s = "tab\there"
print(str(s))
print(repr(s))
print(repr(42), repr(3.5), repr(None))
print(repr("it's"))
tab here
'tab\there'
42 3.5 None
"it's"
For numbers and None, both forms coincide. For strings, repr adds quotes and shows escape sequences, so invisible characters become visible. That makes repr the best debugging tool for text: when two strings "look the same" but == says False, print their reprs and you will spot the trailing space, the tab or the \r from a Windows file. repr chooses double quotes when the string contains a single quote, as with "it's".
Chains of conversions
Conversions can be chained; read them inside out:
text = "3.7"
whole = int(float(text)) # "3.7" -> 3.7 -> 3
nearest = round(float(text)) # "3.7" -> 3.7 -> 4
print(whole, nearest)
3 4
Watch out for float error when scaling, a classic in money calculations:
print(19.99 * 100)
print(int(19.99 * 100))
print(round(19.99 * 100))
1998.9999999999998
1998
1999
int() truncated the almost-1999 down to 1998, losing a cent. round() gives the intended value.
Common mistakes
int()on decimal text.ValueError: invalid literal for int() with base 10: '3.7'. Usefloat()first, or decide whether the input should really be whole.- Expecting
bool("False")to be False. Non-empty strings are always true. - Truncation where rounding was meant.
int(x)drops the fraction; useround(x)when you want the nearest integer. - Forgetting that conversions return new values.
int(text)alone on a line converts and throws away the result;textis still a string. Writen = int(text). - Invisible characters. Text from files often ends in
\nor has stray spaces. Userepr()to see them.
Recap
- Converting creates a new object by calling the target type:
int(),float(),str(),bool(). int(text)is strict about format;int(text, base)reads bases 2-36;int(float)truncates.float()accepts decimal and scientific notation, plus"inf"and"nan".bool()follows truthiness: zero, empty andNoneare false; everything else is true.str()is for humans,repr()for programmers;reprreveals quotes, tabs and other hidden characters.
Going further: read help(int) in the REPL for the full rules of int(x, base). Try ascii("café") and compare it with repr("café").