Learn by reading through in order

Converting Between Numbers and Strings

Convert numbers to strings and back in Python without tripping over TypeError or ValueError — every example runs in your browser.

Why type conversion matters

In Python, you can't just add or compare values of different types as-is.

The classic case is a mix of numbers (int / float) and strings (str). For example, "25" looks like the number 25 at a glance, but to Python it's just two characters lined up — it can't be used in arithmetic.

Mismatched types can't be combined
25int+"yrs"strTypeErrortype mismatchtype mismatch

This is where type conversion (casting) comes in to line up the types. Once you're comfortable with str() / int() / float(), you can freely convert between numbers and strings.

First, let's see what happens if you don't match the types — check the error message. Run the code as-is.

Python Editor

Run code to see output

Number → String (str())

When you pass a number to str(), you get back a string that represents that number.

Whether it's an int, float, or bool, str() turns almost anything into a human-readable string form.

What str() does
25intstr()"25"str-20.5floatstr()"-20.5"strpassto strpassto str

You switch from the number itself to its string representation.

Think of it as prep work before joining (+) values into a sentence.

age = 25
temp = -20.5

# Number -> String
print(str(age))        # '25'
print(type(str(age)))  # <class 'str'>

# Once it's a string, + can join it
print("Age: " + str(age) + " yrs")         # Age: 25 yrs
print("Current temp is " + str(temp) + " deg") # Current temp is -20.5 deg

When to use f-strings instead

Inside an f-string (f"Age: {age} yrs"), values are automatically converted to str, so you don't need to call str() yourself. str() shines when you're building strings with + or .join(), or when you want to lock something in as a string — filenames, log lines, JSON keys, and the like.

Using user = "Alice" and score = 95, build a one-line report.

① Using only str() and +, print "Alice's score is 95".

② Write the same thing with an f-string, without calling str().

Python Editor

Run code to see output

String → Number (int() / float())

For the other direction, use int() and float(). Even if a value looks like a string, as long as its contents are a number, you can convert it and use it in calculations.

Things like user input, CSV columns, and API responses often arrive as str, so converting them to numbers is something you'll do a lot.

Choosing between int() and float()
"100"strint()100int"3.14"strfloat()3.14floatpassto intpassto float

Use int() when you want an integer, and float() when you want to allow decimals.

int("3.14") will fail — it can't do that conversion.

quantity = "12"
price    = "198.5"

# String -> int
q = int(quantity)
print(q + 3)            # 15 (works as a number)

# String -> float
p = float(price)
print(p * q)            # 2382.0 (float, so it has .0)

print(type(q), type(p)) # <class 'int'> <class 'float'>

Non-numeric strings raise ValueError

Passing something that isn't readable as a number, like int("abc") or float("hello"), raises ValueError and stops your program. When converting user input directly, the usual patterns are to check it first with isdigit() or to catch it with try / except (covered in a later chapter).

Let's compute the total for a shopping cart. All the values come in as strings.

You're given unit_price_str = "198", count_str = "5", and a tax rate TAX_RATE = 0.1.

① Convert the count and unit price to numbers with int().

② Multiply the total (unit price × count) by the tax rate and print() the price with tax.

Python Editor

Run code to see output

Common conversion patterns

Finally, here are three conversion patterns that trip people up in practice.

GoalHow to write itResult
Convert "3.14" to an integerint(float("3.14"))3 (decimals truncated)
Count the digits of an intlen(str(1234))4
Round a float to an integerround(3.7) — not int(), use round()4

int("3.14") raises ValueError. That's because int() only accepts strings that look like integers, so a string with a decimal point needs to be run through float() first and then passed to int()two steps.

Also note that int() truncates (drops the decimal part). If you want rounding, use round().

Decimal strings become integers via float()
"3.14"strfloat()3.14floatint()3intpassto floatpassto int

A string with a decimal point can't be passed to int() directly.

Convert it with float() first, then pass the result to int() — a two-step cast to get an integer.

You want to use the price string price_str = "1980.6" as an integer.

① Run int(price_str) as-is and confirm the error, then comment it out.

② Convert it to an integer through float() and print() the result.

Python Editor

Run code to see output

In this article, we walked through type conversion with str() / int() / float(). An easy way to remember it: number → string is for building display output, and string → number is for processing input and data.

QUIZ

Knowledge Check

Answer each question one by one.

Q1Given age = 30, what happens when you run "I am " + age + " years old"?

Q2What's the correct result of running int("3.14")?

Q3What does len(str(1234)) return?