Question

Convert an Integer to a String in Python

pythonstringinteger

Question

How can you convert an integer to a string in Python?

For example, convert the integer 42 into the string "42".

number = 42
text = "42"

How should this conversion be performed, especially when the result will be combined with other text?

Short Answer

You will learn how to turn an integer into text in Python using str(). You will also see when conversion is necessary, how to format numbers inside messages, and how to avoid type-related errors.

Concept

Python values have types. An integer such as 42 is a numeric value (int), while "42" is text (str). They may look similar when printed, but Python treats them differently.

Use the built-in str() function to create a string representation of a value:

str(42)  # "42"

This matters whenever a number must become part of text, such as a log message, URL, filename, screen label, or CSV export. Python does not allow direct concatenation of a string and an integer because that can hide mistakes. Converting explicitly makes your intent clear.

Converting an integer to a string changes its representation, not the original numeric value. The resulting string contains characters and can no longer be used directly in arithmetic without converting it back with int().

Mental Model

Think of an integer as a quantity written on a calculator: it can be added, multiplied, or compared numerically.

A string is the written label for that quantity on a sign. The sign "42" contains two characters, 4 and 2; it is text, not a calculation-ready number.

str() is like copying the calculator's displayed number onto a sign:

quantity = 42       # calculator value
label = str(quantity)  # written sign: "42"

Both describe the same value, but they are used for different jobs.

Take Quiz

Syntax and Examples

Use str(value) to convert an integer to a string.

number = 42
text = str(number)

print(text)        # 42
print(type(text))  # <class 'str'>

Although print(text) displays 42 without quotation marks, text is a string.

Joining a number with text

Convert the integer before using + for string concatenation:

score = 120
message = "Your score is " + str(score)

print(message)  # Your score is 120

Prefer f-strings for messages

An f-string automatically converts the expression inside {} to text:

items = 3
print(f"You have {items} items.")

For simple output messages, f-strings are usually more readable than multiple str() calls.

Converting other integer values

print(str(0))     # "0"
print(str(-15))   # "-15"
print(str(1000))  # "1000"

Step by Step Execution

Consider this example:

visits = 42
message = "Total visits: " + str(visits)
print(message)

Step by step:

  1. visits = 42 stores the integer 42.
  2. str(visits) creates the string "42".
  3. Python concatenates "Total visits: " and "42".
  4. The result, "Total visits: 42", is assigned to message.
  5. print(message) displays:
Total visits: 42

The original visits variable is still an integer:

print(type(visits))       # <class 'int'>
print(type(str(visits)))  # <class 'str'>

Real World Use Cases

Integer-to-string conversion is common whenever a numeric value is displayed, stored as text, or included in another text value.

  • User-facing messages: f"Added {count} products to your cart"
  • Logging: logger.info("Processed " + str(record_count) + " records")
  • URLs: building a path such as /users/42
  • Filenames: creating report_2025.txt
  • CSV and text exports: writing numeric values into text-based files
  • API responses: JSON serializers commonly represent identifiers or values in a required textual format
  • Command-line output: showing progress such as "Downloaded 50 files"

In many cases, formatting tools such as f-strings perform the conversion for you while creating the final message.

Take Quiz

Real Codebase Usage

In production code, developers typically avoid manually concatenating many string fragments. They use f-strings, format(), or a logging framework's parameterized messages.

F-strings for readable messages

def build_user_label(user_id: int, points: int) -> str:
    return f"User {user_id} has {points} points"

Parameterized logging

Python's logging module can defer formatting until the message is needed:

import logging

logger = logging.getLogger(__name__)
user_id = 42
logger.info("Loading profile for user %s", user_id)

Validation at application boundaries

Data from forms, files, and APIs is often text. Convert it to int before arithmetic, then convert it back to str only for display or text output:

def format_order_total(cents_text: str) -> str:
    cents = int(cents_text)
    return f"${cents / 100:.2f}"

This keeps calculations numeric and presentation textual, reducing bugs.

Common Mistakes

Adding a string and an integer directly

This raises a TypeError:

age = 25
message = "Age: " + age  # TypeError

Fix it with str() or an f-string:

message = "Age: " + str(age)
# or
message = f"Age: {age}"

Assuming printed output reveals the type

Both lines display 42, but their types differ:

print(42)
print("42")

Use type() while learning or debugging:

print(type(42))    # <class 'int'>
print(type("42"))  # <class 'str'>

Replacing a number with its string version too early

count = 10
count = str(count)
print(count + 1)  # TypeError

Keep count as an integer if you still need arithmetic. Create a separate display value when necessary:

count = 10
count_text = str(count)
print(count + 1)  # 11

Using int instead of str in the wrong direction

  • str(42) converts an integer to a string.
  • int("42") converts a numeric string to an integer.
text = str(42)
number = int("42")

Confusing conversion with formatting

str(1000000) produces "1000000"; it does not add separators. Use formatting when presentation matters:

value = 1_000_000
print(f"{value:,}")  # 1,000,000

Comparisons

ApproachBest useExampleResult
str(value)Explicitly convert a value for storage or later usetext = str(42)"42"
f-stringInsert values into a readable messagef"ID: {42}""ID: 42"
.format()Format templates, especially older code"ID: {}".format(42)"ID: 42"
% formattingLegacy Python formatting"ID: %s" % 42"ID: 42"
int(text)Convert numeric text back to an integerint("42")42

str() performs conversion. F-strings and other formatting methods are most useful when conversion is part of building a larger piece of text.

Take Quiz

Cheat Sheet

# Integer to string
text = str(42)              # "42"

# Confirm the type
print(type(text))           # <class 'str'>

# Add a number to text
message = "Count: " + str(3)

# Preferred for messages
message = f"Count: {3}"

# Convert text back to an integer
number = int("42")         # 42
  • 42 and "42" are different types.
  • Use str() for an explicit conversion.
  • Use f-strings to embed integers in messages.
  • Do not convert a value to a string if you still need to calculate with it.
  • str(-5) becomes "-5"; str(0) becomes "0".
  • Use format specifiers for display formatting: f"{1234567:,}" gives "1,234,567".

FAQ

How do I convert an integer to a string in Python?

Call str() with the integer:

text = str(42)

Does str() change the original integer?

No. It returns a new string. The original variable remains an integer unless you assign the result back to that variable.

Why do I get TypeError: can only concatenate str (not "int") to str?

You used + to join text and an integer. Convert the integer with str() or use an f-string.

Is "42" the same as 42 in Python?

No. "42" is text, while 42 is an integer. The integer supports arithmetic; the string stores characters.

Should I use str() or an f-string?

Use str() when you need the converted string itself. Use an f-string when you are building a message containing text and values.

How do I convert a string back into an integer?

Use int() if the string contains a valid whole number:

number = int("42")

Can I format an integer with commas while converting it to text?

Yes, use an f-string format specifier:

text = f"{1000000:,}"  # "1,000,000"
Take Quiz

Mini Project

Description

Create a small order-summary formatter. An application often stores quantities and order IDs as integers but must show them in a readable text message. This project practices keeping values numeric for calculations and converting them only when producing output.

Goal

Build a function that returns a formatted order summary containing an integer order ID, quantity, and total item count.

Requirements

  1. Create integer variables for an order ID, items per box, and number of boxes.
  2. Calculate the total number of items using integer arithmetic.
  3. Return a human-readable summary string.
  4. Include the order ID and total item count in the summary.
  5. Use an f-string or explicit str() conversion to include integers in text.
Take Quiz

Keep learning

Related questions

View more