Home › Learn › Python › Strings in depth

Converting types

Lesson 30 of 40. Turn text into numbers safely and back again.

int("42") and float("3.5") parse text into numbers; str(42) goes the other way. int() refuses anything that is not a clean whole number (int("3.5") and int("abc") raise ValueError), and float() accepts decimals and scientific notation but not words.

Before converting user input, check it or catch the error. text.strip().isdigit() is true for a string of digits; for a possibly negative number, strip a leading minus first. The next module covers try/except, which is the general tool; here the check is enough.

raw = " 42 "
if raw.strip().isdigit():
    n = int(raw)
    print(n + 1)   # 43
print(str(3.0) + "!")   # 3.0!

Your task

Write parse_age(text) returning the number as an int when the trimmed text is all digits and None otherwise, to_celsius(f_text) taking a Fahrenheit temperature as text (like "98.6") and returning Celsius rounded to one decimal, and safe_int(text, default) returning the integer value of the text (which may start with a minus sign) or default when it is not a whole number.

Hint 1

text = text.strip(); return int(text) if text.isdigit() else None

Hint 2

Celsius is (F - 32) * 5 / 9; round(..., 1). For safe_int, check text.strip().lstrip("-").isdigit().

Show the solution
def parse_age(text):
    text = text.strip()
    if text.isdigit():
        return int(text)
    return None


def to_celsius(f_text):
    f = float(f_text)
    return round((f - 32) * 5 / 9, 1)


def safe_int(text, default):
    text = text.strip()
    if text.lstrip("-").isdigit():
        return int(text)
    return default

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.