← Python lessons

Python Type Conversion: Checking Text Before int() and float()

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Validating numbers in Python means deciding which text counts as a number for your rule, then converting it with int() or float() without losing data.

Read Data Validation first. This lesson also uses if, elif, else.

What int() and float() accept

int() and float() are more forgiving than .isdigit(). Both ignore spaces around the number and accept a leading sign.

print(int(" 12 "))
print(int("-5"))
print(float("3.5"))
print(float("-0.25"))
print("-5".isdigit())

.isdigit() rejects "-5", but int("-5") gives -5. Choose the check that matches your rule: digits only, or any whole number.

Don't hide a fractional part with int(float(text))

int() on a float truncates: it drops the part after the point, towards zero.

print(int(3.9))
print(int(-3.9))
print(int(float("3.9")))

This prints 3, -3 and 3. So int(float(text)) turns "3.9" into 3 and quietly accepts a value that is not a whole number. Use round() only when rounding is what the rule wants.

Accept negative whole numbers

To allow a leading -, remove at most one and check the rest is digits.

for text in ["-5", "5", "--5", "-", "4.0"]:
    rest = text.removeprefix("-")
    print(text, rest.isdigit())

removeprefix() removes one - only, so "--5" still fails. "-" fails because nothing is left. "4.0" fails because it is written as a decimal.

Check decimal text

A decimal number has digits with at most one . between them. Removing one . and checking for digits catches most bad text.

for text in ["3.5", "12", "3.5.1", ".", "1e3"]:
    ok = text.replace(".", "", 1).isdigit()
    print(text, ok)

"1e3" is rejected here although float("1e3") gives 1000.0. Simple checks like this are stricter than Python. For Python's exact rules, try the conversion and catch the error with try and except.

Note: these checks ignore signs on decimals, spaces, "inf" and "nan", which float() also accepts. Decide whether your data can contain them.

See also: Data Types and Operations, try and except.

Your turn

parse_whole(text) should return the whole number in text, allowing one leading -, or None otherwise. Complete it.

def parse_whole(text):
    # return int(text) when text is digits with at most one leading "-", else None
    return None

for text in ["7", "-7", "--7", "7.5", "-", ""]:
    print(text, parse_whole(text))

Expected output

7 7
-7 -7
--7 None
7.5 None
- None
 None