Python Tutorial › Basics › Type Casting

Python Type Casting

BeginnerLesson 11 of 479 min read8 runnable examples

Type casting means converting a value from one type to another, such as turning the text “42” from input() into the number 42. Python does some conversions for you, and you do the rest with built-in functions named after the types.

Advertisement
In this lesson
  • Implicit vs explicit conversion
  • Convert between numbers and strings
  • Convert between collections
  • Handle values that cannot be converted

Implicit conversion

When you mix an int and a float in arithmetic, Python converts the int to a float for you, so no precision is lost:

Python
qty = 3          # intprice = 19.5     # floattotal = qty * priceprint(total, type(total).__name__)print(True + True)    # bool is a kind of int: True is 1
Output
58.5 float
2

Python will not guess between text and numbers. Mixing them is an error:

Python
age = 30print("Age: " + age)
Output
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print("Age: " + age)
          ~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to str

Explicit conversion functions

FunctionConverts toExampleResult
int(x)whole numberint("42"), int(9.8)42, 9
float(x)decimalfloat("3.5"), float(2)3.5, 2.0
str(x)textstr(100)'100'
bool(x)True/Falsebool(0), bool("no")False, True
list(x)listlist("abc")['a', 'b', 'c']
tuple(x)tupletuple([1, 2])(1, 2)
set(x)setset([1, 1, 2]){1, 2}
dict(x)dictdict([("a", 1)]){'a': 1}

Numbers and strings

Python
age = 30print("Age: " + str(age))        # number to textprint(int("42") + 8)             # text to numberprint(float("3.75") * 2)print(int(9.99), int(-9.99))     # int() truncates towards zeroprint(int("  15\n"))             # surrounding whitespace is ignored
Output
Age: 30
50
7.5
9 -9
15

int() can also read numbers written in other bases:

Python
print(int("ff", 16), int("0b1010", 0), int("777", 8))
Output
255 10 511

Values that cannot be converted

Python
print(int("3.5"))
Output
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'

int() will not read a decimal string. Convert to float first, or catch the error:

Python
print(int(float("3.5"))) for text in ["12", "4.0", "abc"]:    try:        print(text, "->", int(text))    except ValueError:        print(text, "-> not a whole number")
Output
3
12 -> 12
4.0 -> not a whole number
abc -> not a whole number

Converting to bool

bool() returns False for “empty” or zero values and True for everything else.

Python
for v in [0, 0.0, "", "0", "False", [], [0], None]:    print(f"{v!r:8} -> {bool(v)}")
Output
0        -> False
0.0      -> False
''       -> False
'0'      -> True
'False'  -> True
[]       -> False
[0]      -> True
None     -> False
Watch out

bool("False") is True, because it is a non-empty string. To read a yes/no answer, compare the text: answer.strip().lower() in ("yes", "y", "true").

Between collections

Python
letters = list("banana")print(letters)print(set(letters))                    # duplicates removedprint(tuple(letters[:3]))print("".join(letters))               # list of strings back to one string pairs = [("chrome", 120), ("firefox", 118)]print(dict(pairs))print(list({"x": 1, "y": 2}))          # a dict converts to its keys
Output
['b', 'a', 'n', 'a', 'n', 'a']
{'a', 'b', 'n'}
('b', 'a', 'n')
banana
{'chrome': 120, 'firefox': 118}
['x', 'y']

Check your understanding

Predict the output

print(int("7") + float("2.5"), str(7) + str(2.5), int(True))

Quick quiz

1. What does int("3.9") do?

2. What does bool("0") return?

3. Which converts [3, 1, 3] to a collection with only unique items?

Exercise: sum numbers from text

A line of comma-separated numbers arrives as text. Convert it and print the total and the average.

Input
"12, 7.5, 30, 0.5"
Expected output
[12.0, 7.5, 30.0, 0.5]
Total: 50.0
Average: 12.5
Hint 1

split(",") gives the parts as strings; float() converts each one.

Program Practice

Python type casting FAQ

How do I convert a string to an integer in Python?

Use int("42"). If the string may contain a decimal point, use int(float(text)), and wrap it in try / except ValueError for user input.

How do I convert an integer to a string?

Use str(42), or put it in an f-string: f"{42}".

What is the difference between implicit and explicit type conversion?

Implicit conversion is done by Python automatically, such as int to float in 3 * 1.5. Explicit conversion is when you call a function such as int() or str() yourself.

How do I convert a list to a string?

Use ", ".join(items) for a list of strings. For other values, convert each one first: ", ".join(map(str, numbers)).

Leave a Comment