Converting types

Topic 5 of 5 in Values and variables5 min readBeginnerFree course

Overview

Data often arrives in the wrong type: everything from input() is a string, files are text, and web forms send strings. Converting between types — and knowing when not to — is a daily task.

Checking types

Python
type(42)          # <class 'int'>
type("42")        # <class 'str'>
type(4.2)         # <class 'float'>
type(True)        # <class 'bool'>

isinstance(42, int)            # True
isinstance(4.2, (int, float))  # True — is it any kind of number?

type() is handy in the REPL; isinstance() is what you use in code to check a type.

Converting

Function Converts to Examples
int(x) whole number int("42") → 42, int(3.99) → 3, int(" 7 ") → 7
float(x) decimal float("4.5") → 4.5, float(3) → 3.0, float("1e3") → 1000.0
str(x) text str(42) → “42”, str(4.5) → “4.5”, str(True) → “True”
bool(x) True/False bool(0) → False, bool("hi") → True

Conversions that fail

If the text isn’t a valid number, you get a ValueError:

Python
int("seven")    # ValueError: invalid literal for int() with base 10: 'seven'
int("7.0")      # ValueError — int() only accepts whole-number text
int("")         # ValueError
float("4,5")    # ValueError — use a dot, or replace the comma first

int("7.0") catches many people out. Convert via float: int(float("7.0")) is 7.

int() truncates

int() drops the decimal part, moving towards zero — it doesn’t round:

Python
int(3.99)     # 3
int(-3.99)    # -3
round(3.99)   # 4 — use round() if you want rounding

The bool() trap

Every value can be treated as True or False. Empty and zero values are False; everything else is True (Booleans and comparisons lists them all). For strings, that means only the empty string is False:

Python
bool("")         # False
bool("no")       # True!
bool("False")    # True!!
bool("0")        # True

So never convert a yes/no answer with bool(). Compare the text:

Python
subscribed = answer.strip().lower() == "yes"

When NOT to convert

Some values look like numbers but aren’t quantities:

  • postcodes and ZIP codes ("01234" — leading zeros matter),
  • phone numbers ("+44 7700 900123"),
  • IDs and account numbers, card numbers, ISBNs.

You never add or multiply them, and converting can corrupt them (int("01234") is 1234). Keep them as strings. A good rule: convert a value to a number only if you’ll do arithmetic or numeric comparisons with it.

Implicit conversion

Python converts automatically in a few safe places:

  • int and float mix freely in arithmetic: 3 + 1.5 → 4.5.
  • bool behaves like a number: True + True → 2 (handy for counting, as you’ll see later).
  • print() and f-strings convert anything to text for display.

But it never silently converts between text and numbers. "3" + 4 is an error rather than guessing whether you meant "34" or 7 — Python prefers to fail loudly over guessing.

repr() vs str()

When debugging, it can be hard to tell 42 from "42" in printed output. repr() shows a value the way you’d type it in code, quotes included:

Python
print(42, "42")              # 42 42
print(repr(42), repr("42"))  # 42 '42'
print(f"{'42'!r}")           # '42' — !r in an f-string does the same

Rules of thumb: convert input as soon as you read it, convert numbers to text only when you display them, and never use bool() on user text.

Exercise

Clean up messy survey data

A survey stored every answer as text. Convert each value to the right type and print it with its type: age = " 34 " (int, after stripping spaces), rating = "4.5" (float), visits = "7.0" (an int — careful, int("7.0") fails), subscribed = "no" (a bool that is True only for "yes"), and postcode = "01234" (keep it a string — why?). Finally, build the sentence Age 34, rating 4.5/5, 7 visits using an f-string.

Python
age = " 34 "
rating = "4.5"
visits = "7.0"
subscribed = "no"
postcode = "01234"

# Convert each one and print it with type(...)

# Build the sentence with an f-string

Summary

  • type(x) shows a value’s type; isinstance(x, int) checks it.
  • Convert with int(), float(), str() and bool(); invalid text raises ValueError.
  • int() truncates floats towards zero and can’t parse "7.0" directly — use int(float(s)).
  • bool() of any non-empty string is True, even "False" — compare the text instead.
  • Keep identifiers like phone numbers and postcodes as strings; convert only values you calculate with.