Type Conversion
Data often arrives as the wrong type: numbers read from a file or typed by a user are strings, and calculations may need an int where you have a float. Python converts between types explicitly, by calling the type like a function — int(), float(), str() and so on.
Converting to numbers
print(int("42")) print(int(" -7 ")) print(float("3.75")) print(float("1e3")) print(int(9.99)) print(int(True), float(False))
42 -7 3.75 1000.0 9 1 0.0
int() and float() accept strings with surrounding whitespace, and int() on a float truncates the decimal part (it doesn't round).
Invalid conversions raise errors
print(int("3.5"))
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(int("3.5"))
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'Unlike JavaScript, which would return NaN, Python stops with a ValueError. To convert "3.5" to an integer, go through float first: int(float("3.5")). When the input comes from a user, catch the error (lesson 41):
def to_int(text, default=None): try: return int(text) except ValueError: return default print(to_int("12"), to_int("twelve"), to_int("", 0))
12 None 0
Other bases
print(int("ff", 16)) print(int("1010", 2)) print(int("0x1A", 0)) print(hex(255), bin(10), oct(8))
255 10 26 0xff 0b1010 0o10
The second argument to int is the base. Base 0 means "work it out from the prefix".
Converting to strings
print(str(42) + " apples") print(str(3.0), str(None), str([1, 2])) print(repr("hi"), repr(3.0))
42 apples 3.0 None [1, 2] 'hi' 3.0
str() gives a readable form for users; repr() gives an unambiguous form for developers (note the quotes around 'hi'). For mixing values into text, f-strings are usually simpler than str() + concatenation (lesson 10).
Converting to bool
print(bool(0), bool(42)) print(bool(""), bool("False")) print(bool([]), bool([0])) print(bool(None))
False True False True False True False
Empty values — 0, "", empty collections and None — are false; everything else is true. Note that the string "False" is true because it isn't empty. Lesson 11 covers truthiness fully.
Converting between collections
letters = list("hello") print(letters) print(tuple(letters)) print(sorted(set(letters))) print("".join(letters)) print(dict([("a", 1), ("b", 2)])) print(list(range(5)))
['h', 'e', 'l', 'l', 'o']
('h', 'e', 'l', 'l', 'o')
['e', 'h', 'l', 'o']
hello
{'a': 1, 'b': 2}
[0, 1, 2, 3, 4]Converting to a set removes duplicates, but sets have no order — that's why the example sorts it before printing. Going from a list of characters back to a string uses "".join(...), not str().
Implicit conversion is limited
Python converts automatically only between numeric types, where no information is lost in a surprising way:
print(3 + 2.5) print(True + True) print(10 * 1.0)
5.5 2 10.0
Mixing an int and a float gives a float. Anything else — like adding a number to a string — raises a TypeError, which prevents a whole class of bugs.