How to convert between types
Inspect a type
type() reports an object's class. It is especially useful while learning or debugging imported data.
value = "42"
print(type(value))
print(type(42))
print(type(3.14))
Convert text and numbers
int(), float(), and str() create converted values when the input format is valid.
count = int("42")
price = float("19.95")
label = str(2026)
print(count + 1, price * 2, "Year " + label)
Know conversion limits
Converting "3.5" directly to int fails. Convert to float first if truncation is intentional; remember that int() truncates toward zero.
measurement = int(float("3.5"))
print(measurement)
print(int(-3.9)) # -3
Convert collections
Collection constructors consume iterables. Converting to a set removes duplicates but does not preserve a meaningful sequence order.
letters = list("code")
unique = set([1, 1, 2, 3])
fixed = tuple(letters)
print(letters)
print(unique)
print(fixed)