Type conversion is where careful Python code goes wrong. The conversions are not hard. The problem is that the obvious ones have sharp edges. int() cuts off the decimal part instead of rounding down. int('3.9') raises an error, while int(3.9) quietly throws the decimal away. bool('False') is True. And float('nan') is a valid float that is not equal to itself. This lesson gives you the rules and one helper that you can trust.
The previous lesson in this module covered "String vs Numeric Operations: What Actually Changes", and the next lesson in this module is about "Formatting Output with f-strings".
What does Python convert automatically?
Very little, and that is on purpose. Python converts numbers in one situation only, which is when an operation mixes an integer and a float. In that case the integer becomes a float first, because there is no other way to hold the result. Nothing else is converted for you. In particular, text is never turned into a number, because Python cannot know whether '3' meant the number 3 or the price of three tickets.
print('1 + 2.0 ->', 1 + 2.0, '| type:', type(1 + 2.0).__name__)
print('3 / 1 ->', 3 / 1, '| type:', type(3 / 1).__name__)
print('3 + True ->', 3 + True)
print('print() casts ->', 123, 1.5, True, None)
try:
print('5' + 5)
except TypeError as error:
print('"5" + 5 ->', error)
The one automatic conversion that catches people out is the promotion inside mixed arithmetic. 3 / 1 is 3.0 and not 3, because / always gives a float. If you divide counts and you want whole numbers, use // instead.
What are the traps in int() and float()?
There are four of them, and each one gives you a wrong answer instead of an error.
int()cuts off the decimal part, soint(-3.9)is-3. Floor division gives-4. For negative numbers the two rules disagree.int()on text needs a whole number.int('3.9')raisesValueError, so you cannot "just convert a decimal string".float()accepts'nan'and'inf', because those are real float values that are written as words. One stray letter in your data becomes a number that behaves strangely forever.bool()treats every text with something in it asTrue, so the text'False'becomesTrue.
try:
print(int('3.9'))
except ValueError as error:
print("int('3.9') ->", error)
print('int(3.9) ->', int(3.9))
print('int(-3.9) ->', int(-3.9), '| floor would be', -3.9 // 1)
print('int(" 42 ") ->', int(' 42 '))
print("float('nan') ->", float('nan'))
print("float('inf') ->", float('inf'))
print("bool('False') ->", bool('False'))
print('round(3.14159, 2)->', round(3.14159, 2))
Note the last line. round() with no digits argument gives an int, and round() with a digits argument gives a float. That is not a problem by itself, but it means that the type of a rounded value depends on how you wrote the call. It is worth knowing when the result feeds into formatting.
How do you convert between text, numbers and bytes?
Numbers become text with str(), and text becomes a number with int() or float(). int() takes a second argument that says which base the text is written in, and that is how you read a hex or binary identifier.
print("int('0x1f', 16) ->", int('0x1f', 16))
print("int('1010', 2) ->", int('1010', 2))
print("int('ff', 16) ->", int('ff', 16))
print("int(b'42', 10) ->", int(b'42', 10))
print("int('42') ->", int('42'))
text = 'héllo'
encoded = text.encode('utf-8')
print('encoded bytes ->', encoded)
print('decoded back ->', encoded.decode('utf-8'))
print('length in chars ->', len(text))
print('length in bytes ->', len(encoded))
That last comparison is the one to remember. A Python string counts characters, while bytes count octets. An accented letter or an emoji takes several bytes but is still one character, so the two lengths are different. The same idea explains why len() of a string with a family emoji reports one character and not the seven bytes that it uses.
How do you convert safely?
The pattern that survives real data is simple. Clean the text, try the conversion, and return a sensible fallback when it fails. Keep that logic inside one helper, so that the rest of your program never has to think about it.
def to_int(text):
"""Return an int, or None when the text is not a whole number."""
cleaned = text.strip()
try:
return int(cleaned)
except ValueError:
return None
samples = ['42', ' 7 ', '3.5', '', 'abc', '-9']
for sample in samples:
print(repr(sample), '->', to_int(sample))
Notice what the helper does not do, and that is the important part. It does not guess. '3.5' is rejected instead of being cut down, because a value like that usually means that the caller passed the wrong thing, and you would rather know about it. If your data really does contain decimals, write a separate to_float() that accepts them. That way the intent stays visible in the code.
Two more conversions need care. For money, build a Decimal from a string, because Decimal(19.9) carries the float error that you were trying to escape. For fractions, Fraction takes a string directly.
import json
from decimal import Decimal
from fractions import Fraction
price = 19.9
print('float price ->', price)
print('Decimal(price) ->', Decimal(price))
print('Decimal(str) ->', Decimal(str(price)))
print('Fraction string ->', Fraction('1/3') + Fraction('1/6'))
payload = json.loads('{"id": 7, "price": "19.90", "tags": ["a", "b"]}')
for key, value in payload.items():
print(key, type(value).__name__, repr(value))
Look at the JSON output. The parser gives you a real int for the number, a str for the quoted price, and a list for the array. Structured formats carry their types with them, so prefer them to splitting text by hand. And if you ever feel the urge to turn text back into a Python object with eval(), use ast.literal_eval() instead. It can only build literals, and it refuses anything that could run code.
There is a family of conversions that you will meet once you start moving data between structures. list() turns any iterable into a list, tuple() freezes one, and set() removes duplicates. Moving between them is cheap and often useful, especially when a function returns a list but a caller wants to work with a set. The same idea applies to bytes. list(b'abc') gives you the three character codes, and bytes([104, 105]) turns them back into b'hi'.
letters = list('abc')
numbers = list(b'abc')
print('list of chars ->', letters, type(letters).__name__)
print('list of bytes ->', numbers)
print('back to bytes ->', bytes(numbers))
print('unique letters ->', sorted(set('banana')))
print('frozen tuple ->', tuple(letters))
One last trap: turning a number into text and back loses information for floats. str(0.1) gives the shortest text that reads back as the same number, which is usually what you want. But str(float('nan')) gives 'nan', and int() refuses it completely. When a value has to survive a trip through text, check it with math.isfinite() first.
Your turn: write a converter that never crashes
- Write
to_float(text)with the same shape as the helper above, but reject the texts'nan'and'inf'on purpose. They pass a plain conversion and then spoil every comparison that comes after them. - Write
to_bool(text)that accepts'yes','no','true', and'false'in any case, and returnsNonefor anything else. Do not usebool()directly. - Add
to_int_base(text, base)that converts text written in a given base, and use it to read the identifier'0x1F'as 31. - Now build
to_price(text)that returns aDecimal. Check thatto_price('0.10') + to_price('0.20')is exactly0.30while0.10 + 0.20is not. - Finally, write a small script that reads a list of raw texts, converts each one with your helpers, and prints the original text, the converted value, and the type name. Run it on a list with one good value and one broken value on purpose.
Casting cheat sheet
- Python turns an int into a float in mixed arithmetic, and it does nothing else for you.
int()cuts off the decimal part, rejects decimal text, and takes a base argument for hex or binary text.float()accepts'nan'and'inf', so check a converted number before you trust it.bool('False')isTrue, so write your own text-to-bool helper when the text comes from a user.- Build
Decimalfrom a string, keep fractions exact withFraction, and never useeval()to bring text back to life.