Converting types
Overview
Data often arrives in the wrong type: everything from input() is a string, files are text, and web forms send strings. Converting between types — and knowing when not to — is a daily task.
Checking types
type(42) # <class 'int'>
type("42") # <class 'str'>
type(4.2) # <class 'float'>
type(True) # <class 'bool'>
isinstance(42, int) # True
isinstance(4.2, (int, float)) # True — is it any kind of number?type() is handy in the REPL; isinstance() is what you use in code to check a type.
Converting
| Function | Converts to | Examples |
|---|---|---|
int(x) |
whole number | int("42") → 42, int(3.99) → 3, int(" 7 ") → 7 |
float(x) |
decimal | float("4.5") → 4.5, float(3) → 3.0, float("1e3") → 1000.0 |
str(x) |
text | str(42) → “42”, str(4.5) → “4.5”, str(True) → “True” |
bool(x) |
True/False | bool(0) → False, bool("hi") → True |
Conversions that fail
If the text isn’t a valid number, you get a ValueError:
int("seven") # ValueError: invalid literal for int() with base 10: 'seven'
int("7.0") # ValueError — int() only accepts whole-number text
int("") # ValueError
float("4,5") # ValueError — use a dot, or replace the comma firstint("7.0") catches many people out. Convert via float: int(float("7.0")) is 7.
int() truncates
int() drops the decimal part, moving towards zero — it doesn’t round:
int(3.99) # 3
int(-3.99) # -3
round(3.99) # 4 — use round() if you want roundingThe bool() trap
Every value can be treated as True or False. Empty and zero values are False; everything else is True (Booleans and comparisons lists them all). For strings, that means only the empty string is False:
bool("") # False
bool("no") # True!
bool("False") # True!!
bool("0") # TrueSo never convert a yes/no answer with bool(). Compare the text:
subscribed = answer.strip().lower() == "yes"When NOT to convert
Some values look like numbers but aren’t quantities:
- postcodes and ZIP codes (
"01234"— leading zeros matter), - phone numbers (
"+44 7700 900123"), - IDs and account numbers, card numbers, ISBNs.
You never add or multiply them, and converting can corrupt them (int("01234") is 1234). Keep them as strings. A good rule: convert a value to a number only if you’ll do arithmetic or numeric comparisons with it.
Implicit conversion
Python converts automatically in a few safe places:
intandfloatmix freely in arithmetic:3 + 1.5→4.5.boolbehaves like a number:True + True→2(handy for counting, as you’ll see later).print()and f-strings convert anything to text for display.
But it never silently converts between text and numbers. "3" + 4 is an error rather than guessing whether you meant "34" or 7 — Python prefers to fail loudly over guessing.
repr() vs str()
When debugging, it can be hard to tell 42 from "42" in printed output. repr() shows a value the way you’d type it in code, quotes included:
print(42, "42") # 42 42
print(repr(42), repr("42")) # 42 '42'
print(f"{'42'!r}") # '42' — !r in an f-string does the sameRules of thumb: convert input as soon as you read it, convert numbers to text only when you display them, and never use
bool()on user text.
Clean up messy survey data
A survey stored every answer as text. Convert each value to the right type and print it with its type: age = " 34 " (int, after stripping spaces), rating = "4.5" (float), visits = "7.0" (an int — careful, int("7.0") fails), subscribed = "no" (a bool that is True only for "yes"), and postcode = "01234" (keep it a string — why?). Finally, build the sentence Age 34, rating 4.5/5, 7 visits using an f-string.
age = " 34 "
rating = "4.5"
visits = "7.0"
subscribed = "no"
postcode = "01234"
# Convert each one and print it with type(...)
# Build the sentence with an f-stringage = " 34 "
rating = "4.5"
visits = "7.0"
subscribed = "no"
postcode = "01234"
age = int(age.strip()) # int() ignores surrounding spaces, but strip() is clearer
rating = float(rating)
visits = int(float(visits)) # "7.0" → 7.0 → 7
subscribed = subscribed.strip().lower() == "yes" # bool("no") would be True!
# postcode stays a str: int("01234") would lose the leading zero
for value in (age, rating, visits, subscribed, postcode):
print(repr(value), type(value).__name__)
print(f"Age {age}, rating {rating}/5, {visits} visits")Summary
type(x)shows a value’s type;isinstance(x, int)checks it.- Convert with
int(),float(),str()andbool(); invalid text raises ValueError. int()truncates floats towards zero and can’t parse "7.0" directly — useint(float(s)).bool()of any non-empty string is True, even "False" — compare the text instead.- Keep identifiers like phone numbers and postcodes as strings; convert only values you calculate with.