Type conversion
Change values from one type to another
Data often arrives as the wrong type. A number typed by a user arrives as text, and a price read from a file is a string. Type conversion fixes that.
What is type conversion?
Type conversion (also called casting) means turning a value of one type into another type. Python gives you a function for each main type.
| Feature | Converts to | Example | Result |
|---|---|---|---|
| int() | whole number | int("42") | 42 |
| float() | decimal number | float("3.5") | 3.5 |
| str() | text | str(99) | "99" |
| bool() | True / False | bool(0) | False |
Checking a type
Before converting, it helps to know what you have. Use type().
print(type(10)) # <class 'int'>
print(type(10.0)) # <class 'float'>
print(type("10")) # <class 'str'>
print(type(True)) # <class 'bool'>Text to numbers
This is the conversion you'll do most. You can't do math with text, so convert first.
a = "5"
b = "3"
print(a + b) # 53 (joins text!)
print(int(a) + int(b)) # 8 (real math)
price = float("19.99")
print(price * 2) # 39.98int() only accepts text that looks like a whole number. int("3.5") and int("hello") both raise a ValueError. Use float() for decimals.Numbers to text
Use str() when you need to join a number to other text with +. With f-strings, Python does this for you.
tokens = 512
print("Used " + str(tokens) + " tokens")
print(f"Used {tokens} tokens") # same result, no str() neededBetween int and float
print(float(7)) # 7.0
print(int(7.9)) # 7 (cuts off the decimals, no rounding)
print(round(7.9)) # 8 (use round() to round properly)Converting to booleans
bool() follows a simple rule. "Empty" or zero values become False, and everything else becomes True.
print(bool(0)) # False
print(bool("")) # False (empty string)
print(bool([])) # False (empty list)
print(bool(42)) # True
print(bool("hello")) # True
print(bool("False")) # True (it's a non-empty string!)Real example: settings from text
Configuration values, like those from environment variables, always come in as strings. Convert them before use.
max_tokens_text = "300"
temperature_text = "0.7"
max_tokens = int(max_tokens_text)
temperature = float(temperature_text)
print(max_tokens + 100) # 400
print(temperature * 2) # 1.4Common mistakes
- Adding a number to a string:
"Age: " + 30raises aTypeError. Convert withstr()or use an f-string. - Using
int()on decimal text like"2.5". Usefloat()first. - Expecting
bool("False")to beFalse. Any non-empty string isTrue.
What's next?
Now that you can convert types, you're ready to read input from a user. Everything a user types arrives as a string.