Python Type Conversion: Converting Between str, int, float, and bool

Type conversion in Python means turning a value from one type into another, such as changing a text number like "42" into an actual int. You do this with functions like int(), float(), str(), and bool(). This article shows how conversion works, what each function accepts, and the mistakes that cause common errors.

Difficulty: Beginner

Helpful to know first: basic variables, Python values like strings and numbers, and how to use function calls.

How Python Type Conversion Works

Python stores values with a type, and many operations only work when the types match. For example, you cannot add a number and a string directly, because Python does not guess that "5" should mean the number 5. Type conversion gives you an explicit way to tell Python how you want a value interpreted.

The most common conversions are:

  • int() for whole numbers
  • float() for decimal numbers
  • str() for text
  • bool() for truth values

Here is the smallest useful example:

Python
age_text = "21"
age = int(age_text)

print(age + 1)
# Output: 22

Before conversion, age_text is text. After int(), age is a real integer, so Python can do arithmetic with it.

Converting Text to Numbers Without Surprises

Turning a numeric string into an integer

If a string contains only digits, int() converts it to a whole number.

Python
quantity_text = "8"
quantity = int(quantity_text)

print(quantity)
print(type(quantity))
# Output:
# 8
# <class 'int'>

Use this when input comes from a file, form, or the input() function. Text is often the default form of user input, but your program may need a number for math.

Turning a decimal string into a float

Use float() when the number may have a fractional part.

Python
price_text = "19.95"
price = float(price_text)

print(price + 0.05)
# Output: 20.0

This works because float() reads the decimal point and stores the value as a floating-point number. Floating-point numbers are useful for measurements and many calculations, but they can show tiny rounding differences.

Converting strings with spaces or signs

int() and float() can handle leading and trailing whitespace. They also accept plus and minus signs.

Python
text = "  -12  "
number = int(text)

print(number)
# Output: -12

That is useful when cleaning up user input. The spaces do not matter, but the text still must look like a valid number after the spaces are removed.

Converting Numbers to Text for Display

str() turns values into text. This is useful when you want to build messages, write to a file, or combine numbers with other words.

Python
score = 17
message = "Your score is " + str(score)

print(message)
# Output: Your score is 17

Without conversion, Python raises an error if you try to use + between a string and a number. You can also use f-strings, which often make this simpler:

Python
score = 17

print(f"Your score is {score}")
# Output: Your score is 17

Both versions turn the number into text for display. The f-string version is usually easier to read.

How bool() Really Converts Values

bool() does not mean “convert to the words True or False based on what I feel like.” It follows Python's truthiness rules. Some values count as false, and almost everything else counts as true.

The false values you should know first are False, None, numeric zero values like 0 and 0.0, and empty containers like "", [], and {}.

Python
print(bool("hello"))
print(bool(""))
print(bool(0))
print(bool(5))
# Output:
# True
# False
# False
# True

This matters when you read input from a form or file. A non-empty string like "0" is still True, because it is text with characters in it. If you want to treat "0" as the number zero, convert it with int() first.

Common Real-World Conversions in Python Programs

Reading input and doing math

Text entered by a user needs conversion before math works.

Python
hours_text = input("Hours worked: ")
rate_text = input("Hourly rate: ")

hours = float(hours_text)
rate = float(rate_text)

print(f"Pay: {hours * rate}")

After conversion, multiplication works because both values are numbers. Without conversion, Python would treat the inputs as strings.

Parsing CSV-like data

Data from a file often starts as text. You may need to split a line and convert each field separately.

Python
line = "Ada,34,91.5"
name, age_text, score_text = line.split(",")

age = int(age_text)
score = float(score_text)

print(name, age, score)
# Output: Ada 34 91.5

This pattern appears in logs, exports, and simple data files. The important part is that each field is converted to the type the program actually needs.

Formatting output for people

Sometimes your program calculates with numbers but prints text. Conversion makes that possible.

Python
items = 3
total = 12.75

print("Items: " + str(items))
print("Total: $" + str(total))
# Output:
# Items: 3
# Total: $12.75

In real code, f-strings are usually cleaner than many separate calls to str(), but both approaches rely on the same idea: convert the value before combining it with text.

How Type Conversion Behaves in Detail

Type conversion is usually explicit in Python. That means Python does not silently change "5" into 5 for you in most situations. This is one reason Python code is easier to read: the conversion is visible at the line where it happens.

There are a few details that often surprise beginners:

  • int() removes the fractional part when converting from a float, it does not round.
  • bool() follows truthiness rules, not string content.
  • float() can represent very large or very small numbers, but not always exactly.
  • Some conversions fail and raise exceptions instead of guessing.

int() truncates toward zero

If you convert a float to an int, Python drops the decimal part. It does not round to the nearest whole number.

Python
print(int(3.9))
print(int(-3.9))
# Output:
# 3
# -3

If you want rounding, use round() instead of int(). That difference matters in grading logic, measurements, and user interfaces.

Some conversions are not reversible in the way you expect

Converting a float to text and back again can preserve the numeric value, but not always the exact decimal idea you had in mind. Floating-point values are stored in binary, so some decimal numbers cannot be represented exactly.

Python
value = 0.1 + 0.2

print(value)
print(str(value))
# Output:
# 0.30000000000000004
# 0.30000000000000004

This is not a type conversion bug. It is a floating-point representation issue. If you need exact decimal arithmetic for money, use the decimal module from the standard library.

Conversion functions create new values

Type conversion does not change the original object. It creates a new value of a different type.

Python
text = "100"
number = int(text)

print(text)
print(number)
# Output:
# 100
# 100

The original string is still a string. The converted value lives in a separate variable.

Predict the Output

Read each snippet carefully. The goal is to spot what type each value has before Python evaluates the expression.

Snippet 1

Python
x = "5"
y = int(x)
print(y + 1)

What does this print?

Show answer

It prints 6.

x starts as the string "5". int(x) creates the integer 5, so y + 1 becomes 5 + 1.

Snippet 2

Python
text = "0"
print(bool(text))
print(bool(int(text)))

What does this print?

Show answer

It prints True and then False.

The string "0" is not empty, so it is truthy. But int("0") becomes the number 0, and numeric zero is falsy.

Common Mistakes When Converting Types

Adding a string number to an integer without conversion

Input from input() is always a string. If you try to add it to a number, Python raises an error instead of guessing.

Problem: The code mixes a string and an integer in arithmetic, which causes a type error.

Python
age_text = input("Age: ")
print(age_text + 1)
# TypeError: can only concatenate str (not "int") to str

Fix: Convert the input to an integer before using it in math.

Python
age_text = input("Age: ")
age = int(age_text)
print(age + 1)

The corrected version works because both operands are numbers.

Using int() on non-numeric text

int() only works when the text really looks like an integer.

Problem: The string contains letters, so Python cannot interpret it as a base-10 integer.

Python
text = "12px"
print(int(text))
# ValueError: invalid literal for int() with base 10: '12px'

Fix: Clean the text first or extract the numeric part before conversion.

Python
text = "12px"
number_text = text.removesuffix("px")
print(int(number_text))

The fixed version works because the remaining text is a valid integer string.

Using bool() to test user intent instead of truthiness

Beginners often expect bool("False") to give False, but any non-empty string is truthy.

Problem: The code treats the text "False" like the boolean value False, but Python sees a non-empty string.

Python
answer = "False"
print(bool(answer))
# Output: True

Fix: Compare the normalized text to the words you expect.

Python
answer = "False"
is_enabled = answer.strip().lower() == "true"
print(is_enabled)
# Output: False

The corrected version checks the actual text content instead of relying on truthiness rules.

Using int() when you need rounding

int() truncates the decimal part. It does not round to the nearest integer.

Problem: The code expects 3.9 to become 4, but int() removes the fraction instead.

Python
value = 3.9
print(int(value))
# Output: 3

Fix: Use round() when you want normal rounding behavior.

Python
value = 3.9
print(round(value))
# Output: 4

The corrected version works because round() changes the value according to rounding rules instead of dropping the decimal part.

Find the Bug

The code below is meant to read a quantity from text and compute the next quantity. It looks reasonable, but there is a subtle bug in the conversion step. Find it.

Python
quantity_text = "7.0"
quantity = int(quantity_text)

print(f"Next: {quantity + 1}")
Show answer

The bug is that "7.0" is not a valid integer string. int() raises ValueError because of the decimal point.

Fixed code:

Python
quantity_text = "7.0"
quantity = float(quantity_text)

print(f"Next: {quantity + 1}")
# Output: Next: 8.0

The fix works because float() can read a decimal number, and the arithmetic matches the data.

When to Use Each Conversion and When Not To

Use the conversion function that matches the data you actually have. Do not pick a function just because the result seems convenient.

If you have...Use...Why
Whole-number text like "42"int()It creates an integer you can use in counting and indexing.
Decimal text like "3.14"float()It preserves the fractional part.
Any value you want to show to a userstr()It turns values into printable text.
A value you want to test for truthinessbool()It follows Python's truth rules.

Sometimes you do not need conversion at all. For example, if you only want to compare text, keep it as a string. Converting too early can throw away information, such as leading zeros in IDs or ZIP codes.

Keep values as strings when the exact text matters, not the numeric value.

Interview Questions About Python Type Conversion

What is the difference between int() and round()?

int() removes the fractional part by truncating toward zero. round() rounds to the nearest integer using rounding rules. Use int() when you want truncation, and round() when you want a rounded result.

Why does bool("False") return True?

Because bool() checks whether the string is empty, not whether its text says False. Any non-empty string is truthy in Python.

Why does Python not convert types automatically more often?

Python avoids guessing because guessing can hide bugs. If Python silently changed strings into numbers in every expression, code would be harder to read and easier to misuse. Explicit conversion makes the programmer's intent clear.

Try It Yourself

Write a small program that:

  • stores the string "15" in a variable
  • converts it to an integer
  • adds 5
  • prints the result

Expected output:

Python
20

Hint: Use int() before you add the numbers.

Show solution
Python
value_text = "15"
value = int(value_text)

print(value + 5)
# Output: 20

Summary

  • Type conversion changes a value from one type to another.
  • Use int() for whole numbers, float() for decimals, str() for text, and bool() for truthiness.
  • int() truncates decimal values instead of rounding them.
  • bool() treats non-empty strings as True, even if the text says "False".
  • Conversion functions create new values; they do not change the original object.
  • When text does not match the expected format, Python raises ValueError or TypeError.

Next, learn about input() and numeric operators so you can convert user-entered text into values your programs can actually use.