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.
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 calls.
Step by Step Execution
Consider this example:
visits = 42
message = "Total visits: " + str(visits)
print(message)
Step by step:
visits = 42stores the integer42.str(visits)creates the string"42".- Python concatenates
"Total visits: "and"42". - The result,
"Total visits: 42", is assigned tomessage. 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.
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) -> :
cents = (cents_text)
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
Comparisons
| Approach | Best use | Example | Result |
|---|---|---|---|
str(value) | Explicitly convert a value for storage or later use | text = str(42) | "42" |
| f-string | Insert values into a readable message | f"ID: {42}" | "ID: 42" |
.format() | Format templates, especially older code | "ID: {}".format(42) | "ID: 42" |
% formatting | Legacy Python formatting |
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
42and"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 if the string contains a valid whole number:
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
- Create integer variables for an order ID, items per box, and number of boxes.
- Calculate the total number of items using integer arithmetic.
- Return a human-readable summary string.
- Include the order ID and total item count in the summary.
- Use an f-string or explicit
str()conversion to include integers in text.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.