Type Conversion

Turning text into numbers and back, what converts silently, and what raises rather than guessing.

Overview

Turning text into numbers and back, what converts silently, and what raises rather than guessing.

In this guide
  1. The constructors
  2. Text in, text out
  3. Floats are not decimals
  4. bool() is broader than it looks
  5. Conversion is not the same as checking
  6. The float trap
  7. Truthiness is a conversion too
  8. Implicit conversion, and where Python refuses
  9. What each constructor actually accepts
  10. Parsing a boolean from text
  11. Where conversion loses information
  12. The numeric types beyond int and float
  13. Convert once, at the edge
  14. The one conversion Python does silently
  15. Questions people ask about Type Conversion
  16. Type Conversion: recap in one screen

conversion.py

conversion.py Python 3
Output

                    

conversion_care.py

conversion_care.py Python 3
Output

                    

Worth knowing

The type names are the conversions: int(), float(), str(), list().
int("3.9") raises; int(3.9) truncates toward zero.
round(2.5) is 2, not 3 - it rounds to the nearest even on a tie.
bool("0") is True. Any non-empty string is.

Type Conversion: A Practical Guide

Python doesn't convert types behind your back. You ask, using the type name as a function. It either succeeds or raises — it won't guess.

The constructors

int("42")    float("3.14")    str(42)    list("abc")    bool("")

Each type name doubles as its constructor. Call it with a value and it returns that value converted to the target type. That is why there is no separate casting syntax in Python: the type itself is the converter.

The most common conversion is from string to number. The input() function always returns a string, even when the user types digits. Before you can do arithmetic on that input, you need to convert it. int("42") gives the integer 42. float("3.14") gives the floating-point number 3.14. If the string does not contain a valid number, both raise a ValueError. That is the correct behavior: a silent wrong result would be worse than a loud error.

Going the other direction, str(42) gives the string "42". You need this when concatenating a number with other text using the + operator. "score: " + 42 is a TypeError because Python does not convert types implicitly. You must write "score: " + str(42) or use an f-string. F-strings call str() on each value automatically, which is one reason they replaced concatenation.

list("abc") splits the string into individual characters: ["a", "b", "c"]. tuple([1, 2, 3]) wraps a list into a tuple. set([1, 2, 2, 3]) drops duplicates and gives {1, 2, 3}. Each constructor accepts any iterable of the right shape and builds the target container from it.

bool() is the truthiness test. bool("") is False. bool("hello") is True. bool(0) is False. bool(42) is True. The rule is simple: empty and zero values are false, everything else is true. You rarely call bool() directly because if and while apply the same test automatically. But understanding what bool() returns helps you predict how conditionals behave.

int() can also parse numbers in other bases. int("ff", 16) gives 255. int("1010", 2) gives 10. The second argument is the base of the input string.

This page covers the main type constructors, string-to-number conversion, the errors that arise from invalid input, the truthiness rules behind bool(), and base conversion with int().

Text in, text out

any of it read from a user, a file or a network arrives as text. "10" + "10" is "1010". No error is raised. Concatenating strings is a just right sensible thing to do. Converting is on you:

int(text) + int(text)

This is the single most common source of confusion for beginners. It isn't really about conversion. It's about noticing that input is always a string.

Floats are not decimals

0.1 + 0.2 == 0.3  # False

Binary floating point can't represent 0.1 just. The sum is a hair off. This isn't a Python quirk. It's how floats work all over. Compare with a handling, round before checking, or use decimal.Decimal for money.

bool() is broader than it looks

bool("0") is True, because the string isn't empty. Falsy values are: 0, 0.0, "", [], {}, set(), None and False. All else is truthy, including "False".

Conversion is not the same as checking

int("42") converts. isinstance(x, int) checks. Reaching for the wrong one is common, and the gap matters because conversion can fail loudly while a check never does.

The Python habit is to attempt the conversion inside a try rather than to validate first with a regular formula or a series of isdigit calls. The attempt is the authoritative test - it knows about signs, whitespace, underscores in numeric literals and every other detail your hand-written check would miss.

def as_int(text, default=None):
    try:
        return int(text)
    except (TypeError, ValueError):
        return default

Catching both matters: ValueError for text that isn't a number, TypeError for None or a list arriving where a string was expected.

The float trap

int("3.9") raises, which surprises people who expect it to truncate. The string isn't an int literal, so the conversion refuses rather than guessing. int(3.9) on an actual float does truncate, toward zero, so int(-3.9) is -3 rather than -4.

If you want rounding rather than truncation, round is the function, and it has its own surprise: it rounds halves to the nearest even number, so round(2.5) is 2 and round(3.5) is 4. That is deliberate - it avoids the upward bias you get from always rounding halves up - and it's worth knowing before you conclude a thing is broken.

Converting a string that might hold a decimal is a two-step: int(float("3.9")).

Truthiness is a conversion too

bool(x) follows the same rules as if x. This Means empty containers, zero and None all convert to False. That makes bool at times handy for norming a value, and it makes bool("False") a well-known trap: the string is non-empty, so it's True. Parsing a boolean from text needs an clear mapping, not a conversion.

Implicit conversion, and where Python refuses

Python converts numeric types automatically when it can do so without losing info: 1 + 2.0 gives 3.0, and checking an int with a float works as expected. It refuses to convert between strings and numbers, which is why "3" + 4 raises rather than guessing whether you meant 7 or "34".

That refusal is a feature. Languages that do guess give a class of bug where a number arrives as a string from a form or a file and all continues to work until the math silently turns concatenation. In Python that fails at once, at the line in charge.

What each constructor actually accepts

The type names double as conversions. Each has its own idea of what it will take. Seeing them side by side drops most of the surprises:

print(int("  42  "), int("1_000"), int("ff", 16))
print(float("1e3"), float("  .5 "))
print(list("abc"), list({"a": 1}), tuple([1, 2]))
print(str([1, 2]), str(None))
42 1000 255
1000.0 0.5
['a', 'b', 'c'] ['a'] (1, 2)
[1, 2] None

int handles nearby whitespace and the underscores Python allows in numeric literals, and takes a base as a second arg — which is how you read hexadecimal, binary and octal from text without writing a parser.

list on a dict gives its keys, not its items, which catches people who expected pairs. list on a string gives characters, which is at times what you want and more often a sign that split was meant.

str never fails. each object has a string form, so str(x) always returns a thing — which is convenient and means a bug can travel a long way disguised as text. str(None) is the string "None", and a "None" written into a CSV column is a classic way to lose the gap between missing and present.

Parsing a boolean from text

There's no conversion for this, and reaching for bool is the mistake everyone makes once:

print(bool("False"), bool("0"), bool(""))
True True False

bool on a string asks only whether the string is empty. "False" and "0" are both non-empty, so both are True. This Is just backwards from what the text says.

Reading a boolean out of a config file, an environment variable or a form means deciding what counts, and then saying so:

TRUE = {"1", "true", "yes", "on"}

def as_bool(text):
    return str(text).strip().lower() in TRUE

That is a policy rather than a conversion. This Is why the language doesn't provide one — different formats disagree about whether "y", "on" or "enabled" should count, and about what an unrecognised value means. Deciding by name is the point.

Where conversion loses information

Some conversions are exact and some throw info away, and knowing which is which blocks a family of quiet bugs.

int(3.9) discards the fractional part. int from a large float loses precision before it even starts, because the float never held the exact value. float(some_big_int) is worse: ints in Python are unbounded, floats are not, so a enough large int converts to a float that is merely nearby, and converting back doesn't return the first.

str of a float is lossy in the other direction once, though modern Python prints the shortest string that round-trips just, so float(str(x)) == x holds.

set(items) discards duplicates and order. dict(pairs) discards all but the last value for each repeated key. Neither reports what it dropped, and both are at times used on purpose for just that effect. Which is why the loss has to be intentional rather than found.

The habit worth forming: when a conversion narrows. Float to int, list to set, any of it to str. Ask what happens to what doesn't fit. When it widens, as int to float or str to list, there's often nothing to worry about.

The numeric types beyond int and float

int and float cover most work, and two more exist for cases where floats give the wrong answer.

decimal.Decimal shows numbers in base ten, so Decimal("0.1") * 3 is just Decimal("0.3") rather than a hair off. It's the right type for money, invoices, tax and any of it where a result will be checked against a figure a person found. Build it from a string, not a float: Decimal(0.1) faithfully captures the float's error. This Defeats the point.

fractions.Fraction holds an exact ratio. So Fraction(1, 3) * 3 is just 1. It's the right type for exact rational math, and it's slower and grows in memory as denominators times. So It belongs in maths rather than in stored data.

Both convert to and from the plain types, and both interoperate with int — but mixing either with float in one formula converts back to float and reintroduces the error you were avoiding. This Is the trap. If a math is meant to be exact, each value in it has to be the exact type.

complex also exists, written 3+4j, and is truly used in signal processing and geometry. It's worth knowing mainly so that j in a numeric literal isn't a mystery.

Convert once, at the edge

The thread running through this page is that conversion is a choice, and the handy discipline is to make each choice just once. Here The data enters the program.

A value read from a file, a form, an environment variable or an API is text. If it's converted at the point of use, each use site repeats the conversion, each use site has to handle the failure, and the sites will eventually disagree — one treats an empty string as zero, another as an error, a third crashes. The type of the value turns a thing a reader has to infer from context.

Converting at the boundary means one place decides what a bad value means, and all after that point works with a real int, date or Decimal. The error, when it comes, names the input and the field rather than surfacing as a TypeError deep in a math.

This is the same arg as validating nested data at the boundary, and the same arg for keyword-only params: push the ambiguity to one place, as early as possible, and let all downstream lean on what it was given.

The one conversion Python does silently

All on this page says Python refuses to convert without being asked, which is true with one systematic exception: numeric promotion.

Mixing an int and a float in an formula converts the int to a float first, so 1 + 2.0 gives 3.0 and 1 / 2 gives 0.5 rather than 0. Mixing a bool with a number treats True as 1 and False as 0, which is why sum([True, False, True]) is 2 — at times handy for counting how many rules held, and at times a surprise.

The rule is that Python converts within the numeric tower only, and only in the widening direction, where nothing is lost. int to float is allowed. str to any of it isn't. That is why True + 1 works and "1" + 1 doesn't, which looks inconsistent until you see the boundary it's drawing.

The one place the widening does lose a thing is very large ints, where converting to float loses precision though the conversion is nominally widening. It's the exception to the exception, and it only bites at magnitudes most programs never reach.

Questions people ask about Type Conversion

Why does int("3.9") fail when int(3.9) works? The string is not an int literal, so it refuses rather than choosing a rounding direction. Use int(float("3.9")) when you mean truncation.

How do I convert a list of strings to numbers? [int(x) for x in items], or list(map(int, items)).

What is the difference between str and repr? str is for people, repr is for programmers and aims to be unambiguous. print uses str. The interactive prompt and containers use repr.

Why is 0.1 + 0.2 not 0.3? Binary floating point can't represent those decimals just. Use math.isclose to compare, or decimal.Decimal for money.

Does int() round or truncate? Truncates toward zero, so int(-3.9) is -3. round is the one that rounds.

How do I convert between a string and bytes? text.encode("utf-8") and data.decode("utf-8"). Both need an encoding, and guessing is where mojibake comes from.

Can I convert a dict to a list of pairs? list(d.items()). Plain list(d) gives the keys.

Should I annotate types instead of converting? They're different jobs. An annotation docs and is checked by tools. It doesn't convert any of it at runtime.

How do I convert a string to a date? datetime.strptime(text, fmt) with an clear format, or datetime.fromisoformat for ISO-8601 text. Neither guesses.

What does int() with no arg give? Zero. each numeric constructor called with nothing returns its zero value, which is at times handy as a default factory.

Type Conversion: recap in one screen

  • Each type's name is its conversion. There's nothing extra to store.
  • Input is always text, and Python will never convert it for you — that refusal is what makes "3" + 4 an error rather than a silent bug.
  • int from a string is strict, int from a float truncates toward zero, and round rounds halves to even.
  • bool on a string only asks whether it's empty. Parsing a boolean from text needs an clear mapping.
  • Narrowing conversions lose info silently — duplicates, order, precision, the difference between missing and "None".

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `int("3.9")` do?

  2. `round(2.5)` returns what?

  3. `bool("0")` is:

Cheat sheet

Type Conversion

Convert between strings, integers and floats with int(), float() and str(), and see the errors Python raises when a conversion is impossible.

PYTHON · vizlearn.in/python/type_conversion.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.