Python Casting
Casting converts a value from one type to another. Python uses the target type's name as a function.
The three big ones
PYTHON
n = int('42') # str → int
f = float('3.14') # str → float
s = str(99) # int → str
print(n, f, s)
What fails
| Cast | Result |
|---|---|
int('forty-two') | ValueError |
int('3.14') | ValueError — int() doesn't parse floats from strings |
int(3.99) | 3 — truncates toward zero |
float('not a number') | ValueError |
str(anything) | Always works |
Boolean casting
bool(x) returns False for "empty" values, True for everything else:
PYTHON
print(bool(0), bool(0.0), bool(''), bool([]), bool({}), bool(None)) # all False
print(bool(1), bool(-1), bool('hi'), bool([0])) # all True
Collection casting
PYTHON
list('abc') # ['a', 'b', 'c']
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 1, 2]) # {1, 2}
dict([('a', 1)]) # {'a': 1}
Tip: Wrap user input in
try/except ValueError. The first time someone types "ten" instead of "10", the exception is what tells you.Example
Example
n = int('42')
f = float('3.14')
s = str(99)
print(n, f, s, type(n).__name__, type(f).__name__, type(s).__name__)
Try it Yourself »
Exercise
Convert the string "42" to an integer.
n =
('42')
Three letters; same as the type name.
Discussion
Loading…