In Python, we use the name of the type as a function to perform the conversion: int(), str(), float(), and bool().
str()
Every single thing in Python can be turned into a string. This is usually the safest conversion. It’s mostly used when you want to combine numbers with text (if you aren’t using F-strings).
age = 28
message = "I am " + str(age) # Turns 28 into "28"
print(message)
int() and float()
Converting to numbers is a bit more “dangerous” because the data must actually look like a number, or Python will throw a ValueError.
When you convert a float (decimal) to an int, Python doesn’t round the number. It truncates it - simply chops off the decimal and throws it away.
pi = 3.99
print(int(pi)) # Output: 3 (It does NOT round to 4!)
Use the round() function to get 4.
x = 3.7
print(int(x)) # 3
print(round(x)) # 4
You can turn the string "10" into an integer, but you cannot turn "10.5" into an integer directly. You would have to go through float first.
score = int("100") # Works
# price = int("19.99") # CRASH! (ValueError)
price = float("19.99") # Works
bool()
The rule in Python is very simple: Empty is False, Full is True.
Only a few specific things are considered “Empty” or False:
- The number
0 - An empty string
"" - An empty list
[], dict{}, or tuple() - The value
None
Everything else is True:
- Any number other than
0(even negative numbers like-1areTrue). - A string with even a single space
" "isTrue.
print(bool(0)) # False
print(bool(0.001)) # True
print(bool("")) # False
print(bool(" ")) # True (The space counts as content!)
list()
Use list() when you want to take a fixed collection (like a tuple or a string) and turn it into something you can change (add to, remove from, or sort).
- From a String: It breaks the string into individual characters.
- From a Tuple: It converts the “locked” tuple into a flexible list.
# From string to list
print(list("ABC")) # ['A', 'B', 'C']
# From tuple to list
locked_data = (1, 2, 3)
flexible_data = list(locked_data)
flexible_data.append(4)
print(flexible_data) # [1, 2, 3, 4]
tuple()
Use tuple() when you want to “freeze” a list so it can no longer be changed. This is safer for data that shouldn’t be touched by other parts of your code.
shopping_list = ["Apples", "Milk"]
frozen_list = tuple(shopping_list)
# frozen_list.append("Doritos") # CRASH! Tuples have no append method.
Implicit vs. Explicit Conversion
- Explicit (Casting): When you manually use a function like
int(var). - Implicit: When Python does it for you automatically.
The most common implicit conversion happens when you add an int to a float. Python automatically promotes the int to a float so you don’t lose the decimal data.
a = 5 # int
b = 2.0 # float
c = a + b
print(c) # 7.0 (Python turned the result into a float)