Python Casting
Python casting means converting a value from one data type to another. You do it with built-in functions named after the type: int(), float(), str(), bool(), list() and so on. Casting is essential when you read numbers from text, such as user input or a file.
Convert String to int and float
age_text = "27"
height_text = "1.75"
age = int(age_text)
height = float(height_text)
print(age + 1)
print(height * 100)28 175.0
Without int(), "27" + 1 would raise a TypeError because Python will not add text to a number. Casting makes the intent clear.
Convert Numbers to Strings
str() turns any value into text. This is needed when you join numbers to other strings with the + operator.
items = 3
message = "You have " + str(items) + " items in your cart"
print(message)You have 3 items in your cart
Float to int
int() on a float cuts off the decimal part. It does not round. Use round() first if you want the nearest whole number.
print(int(9.99))
print(int(-9.99))
print(round(9.99))
print(float(5))9 -9 10 5.0
Handling Invalid Conversions
Converting text that does not look like a number raises a ValueError. Wrap the conversion in try...except to handle bad input gracefully.
for text in ["42", "4.2", "forty-two"]:
try:
print(int(text))
except ValueError:
print("Cannot convert:", text)42 Cannot convert: 4.2 Cannot convert: forty-two
Other Useful Conversions
- bool(value): empty values (0, "", [], None) become False, everything else True
- list("abc") gives ['a', 'b', 'c']
- tuple([1, 2]) and set([1, 1, 2]) convert between collections
- int("ff", 16) converts a hexadecimal string, giving 255
Frequently asked questions
How do I convert a string to an integer in Python?
Call int() on it, for example int("15") returns 15. If the string might not be a valid number, catch ValueError with try...except.
How do I convert "4.5" to an int?
int("4.5") fails because the text has a decimal point. Convert to float first and then to int: int(float("4.5")) returns 4.
What is implicit type conversion in Python?
Python converts automatically in safe cases, such as 3 + 1.5 where the int is promoted to a float. It never automatically converts between text and numbers.