Python Casting
Learn how to convert between different data types in Python using casting.
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
Casting in Python is therefore done using constructor functions:
int()- constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)float()- constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)str()- constructs a string from a wide variety of data types, including strings, integer literals and float literals
Integers
Example
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3Floats
Example
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2Strings
Example
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'Type Conversion Examples
Converting to Integer
# From float to int
num_float = 9.8
num_int = int(num_float)
print(num_int) # Output: 9
# From string to int
str_num = "123"
num_int = int(str_num)
print(num_int) # Output: 123
# From boolean to int
bool_val = True
num_int = int(bool_val)
print(num_int) # Output: 1Converting to Float
# From int to float
num_int = 10
num_float = float(num_int)
print(num_float) # Output: 10.0
# From string to float
str_num = "3.14"
num_float = float(str_num)
print(num_float) # Output: 3.14
# From boolean to float
bool_val = False
num_float = float(bool_val)
print(num_float) # Output: 0.0Converting to String
# From int to string
num_int = 42
str_num = str(num_int)
print(str_num) # Output: '42'
# From float to string
num_float = 3.14159
str_num = str(num_float)
print(str_num) # Output: '3.14159'
# From list to string
my_list = [1, 2, 3]
str_list = str(my_list)
print(str_list) # Output: '[1, 2, 3]'Common Casting Errors
Be careful when casting, as some conversions may raise errors:
Invalid String to Integer
# This will raise a ValueError
x = int("hello") # ValueError: invalid literal for int()Invalid String to Float
# This will raise a ValueError
y = float("abc") # ValueError: could not convert string to floatSafe Casting with Error Handling
def safe_int_cast(value):
try:
return int(value)
except ValueError:
print(f"Cannot convert '{value}' to integer")
return None
# Usage
result = safe_int_cast("123") # Returns 123
result = safe_int_cast("hello") # Prints error message, returns NoneAdvanced Casting
Boolean Casting
# Converting to boolean
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("text")) # True
print(bool([])) # False
print(bool([1, 2])) # TrueList and Tuple Casting
# Converting between list and tuple
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3, 4)
my_tuple = (5, 6, 7, 8)
my_list = list(my_tuple)
print(my_list) # [5, 6, 7, 8]
# Converting string to list
text = "hello"
char_list = list(text)
print(char_list) # ['h', 'e', 'l', 'l', 'o']Casting Can Fail — Handle It
Converting text that is not a valid number raises ValueError. Guard user input with try/except or a validation check.
int("abc") # ValueError: invalid literal for int() with base 10
raw = "42x"
try:
n = int(raw)
except ValueError:
print(f"'{raw}' is not a whole number")
# check first
print("42".isdigit()) # True
print("4.2".isdigit()) # FalseWatch Out For These Conversions
| Expression | Result | Why |
|---|---|---|
int(3.9) | 3 | Truncates toward zero (no rounding) |
int("3.9") | ValueError | Not a valid int string |
float("3.9") | 3.9 | Valid float string |
bool(0), bool("") | False | "Falsy" values |
bool("False") | True | Any non-empty string is truthy! |
int(3.9) gives 3, not 4 — it truncates. Use round(3.9) to round to the nearest integer.
Try It Yourself
Exercise 1: Convert the string "3.5" to a number and add 1 to it.
Show solution
print(float("3.5") + 1) # 4.5Exercise 2: Safely read an integer, printing an error if the input is not numeric.
Show solution
text = "12ab"
try:
print(int(text))
except ValueError:
print("Please enter a whole number.")Key Takeaways
- Cast with
int(),float(),str(),bool(). int()truncates floats; useround()to round.- Invalid conversions raise
ValueError— wrap risky casts in try/except. - Any non-empty string is truthy, so
bool("False")isTrue.
📘 Real-World Deep Dive
User input, network payloads, and database results are always strings until you convert them. Correct casting prevents half the "off-by-one" / "TypeError" bugs in any non-trivial script.
Real-Life Scenario
A CLI that accepts a duration like <code>"2h 35m"</code> and turns it into a number of seconds for scheduling.
Real-Life Example
import re
from datetime import timedelta
DURATION_RX = re.compile(
r"(?P<hours>\d+)h\s*"
r"(?:(?P<minutes>\d+)m)?\s*"
r"(?:(?P<seconds>\d+)s)?",
re.IGNORECASE,
)
def parse_duration(s: str) -> int:
m = DURATION_RX.fullmatch(s.strip())
if not m:
raise ValueError(f"unparseable duration: {s!r}")
h = int(m["hours"] or 0)
mi = int(m["minutes"] or 0)
se = int(m["seconds"] or 0)
return int(timedelta(hours=h, minutes=mi, seconds=se).total_seconds())
for raw in ["1h", "2h 35m", "45s", "0H 0M 30S", "bogus"]:
try:
print(f"{raw!r:>14} -> {parse_duration(raw)}s")
except ValueError as e:
print(f"{raw!r:>14} -> ERROR: {e}")Expected Output
'1h' -> 3600s
'2h 35m' -> 9300s
'45s' -> 45s
'0H 0M 30S' -> 30s
'bogus' -> ERROR: unparseable duration: 'bogus'Common mistakes
int("3.14")raisesValueError— callfloat(...)first, or useDecimal.bool("False")isTruebecause the string is non-empty; cast viastr(x).lower() == "true"instead.list(dict)gives you the keys, not the values — uselist(d.values())explicitly.
🚀 Performance & Best Practices
- Use
int(s, base=16)to parse hex without a manual"0x"strip. - For large numeric strings,
int(...)is fast;Decimal(...)is slow — pick the precision you actually need. - Convert once at the system boundary, then keep typed objects throughout the program.
🧪 Try It Yourself
- Extend
parse_durationto accept days (3d) and weeks (1w). - Write a
parse_datecompanion that usesdatetime.fromisoformatwithint()on the year/month/day. - Catch
ValueErrorinparse_durationand returnNoneinstead of raising.