How to concatenate a string and int in Python
Learn how to concatenate strings and integers in Python. This guide covers various methods, tips, real-world uses, and debugging common errors.

To join a string and an integer in Python, you must convert the number to a string. This fundamental task is key for dynamic output, log messages, and formatted data displays.
In this article, you'll discover methods from f-strings to the str() function. You'll get practical tips, see real-world applications, and learn how to debug common type errors effectively.
Using str() to convert integers to strings
name = "John"
age = 30
result = name + " is " + str(age) + " years old."
print(result)--OUTPUT--John is 30 years old.
The + operator in Python is context-sensitive. It performs mathematical addition for numbers but string concatenation for text. When you attempt to use it with mixed types like a string and an integer, Python raises a TypeError because the intended operation is ambiguous.
By wrapping the integer variable age in the str() function, you perform an explicit type conversion. This tells Python to treat the number as text, resolving the ambiguity and enabling the + operator to concatenate all the pieces into a single, coherent string.
Basic concatenation methods
While using str() with the + operator gets the job done, Python offers more elegant approaches like f-strings, the .format() method, and the % operator.
Using f-strings for clean string interpolation
name = "Jane"
age = 25
result = f"{name} is {age} years old."
print(result)--OUTPUT--Jane is 25 years old.
F-strings, or formatted string literals, offer a modern and readable way to embed expressions inside string literals. You simply prefix the string with an f and write expressions inside curly braces {}. Python automatically evaluates these expressions and inserts their string representations.
- Readability: The syntax is concise, making your code easier to read and write.
- Performance: F-strings are generally faster than other formatting methods.
- Convenience: You don't need to call
str()manually; the conversion is handled for you.
Using the .format() method
name = "Bob"
age = 40
result = "{} is {} years old.".format(name, age)
print(result)--OUTPUT--Bob is 40 years old.
The .format() method is a versatile way to build strings. You call it on a string containing curly brace {} placeholders, and the method replaces them with the variables you provide. By default, it matches them in order.
- Versatility: It was the standard before f-strings and remains useful, especially in older codebases.
- Readability: It keeps the template string separate from the values, which can improve clarity in complex formatting scenarios.
This method also handles the conversion of non-string types automatically, so you don't need an explicit str() call.
Using the % operator for string formatting
name = "Alice"
age = 35
result = "%s is %d years old." % (name, age)
print(result)--OUTPUT--Alice is 35 years old.
The % operator is an older string formatting method inherited from C's printf function. It uses format specifiers like %s for strings and %d for integers as placeholders within the template string.
- Legacy Style: While it still works, this method is less common in modern Python, which favors f-strings.
- Type Specificity: You must match the specifier to the data type—
%sfor a string,%dfor an integer—or you'll get an error.
The variables are passed in a tuple and matched to the specifiers in order.
Advanced concatenation techniques
For more complex scenarios, like joining lists of items, you can use advanced techniques like the join() method, the map() function, and custom functions.
Using join() with converted types
name = "Mike"
age = 28
items = [name, "is", str(age), "years old"]
result = " ".join(items)
print(result)--OUTPUT--Mike is 28 years old.
The join() method is a highly efficient way to construct a string from a list of items. You call it on a separator string—in this case, a space " "—and it connects every element from an iterable, like the items list, into a single string.
- This method works exclusively with strings. You must convert any non-string elements, which is why
str(age)is necessary before joining. - It’s especially powerful for assembling strings from many parts, as it’s generally faster than using the
+operator in a loop.
Creating a concatenation function with type handling
def concat(*args):
return "".join(str(arg) for arg in args)
result = concat("The answer is ", 42, "!")
print(result)--OUTPUT--The answer is 42!
For a reusable solution, you can define a custom function. The concat function uses *args to accept any number of arguments, which are then processed within a generator expression.
- The expression
(str(arg) for arg in args)loops through each argument, converting it to a string withstr(). This ensures all items are the correct type. - Finally,
"".join()stitches the resulting strings together. This creates a powerful utility that gracefully handles mixed data types without repetitive code.
Using map() for efficient conversion and joining
data = ["User:", "Alex", "ID:", 12345, "Level:", 7]
result = " ".join(map(str, data))
print(result)--OUTPUT--User: Alex ID: 12345 Level: 7
The map() function provides a concise way to apply another function to every item in an iterable. Here, map(str, data) iterates through the data list and applies the str() function to each element, converting all integers to strings on the fly. The resulting map object—an efficient iterator—is then consumed by the join() method.
- Efficiency: It’s often faster than an explicit
forloop for simple transformations. - Readability: This approach clearly signals your intent to transform every item in the collection.
Move faster with Replit
Replit is an AI-powered development platform designed to turn your ideas into working software. Instead of just writing code, you can describe what you want to build, and our AI software engineer, Replit Agent, brings it to life—complete with a user interface, databases, and deployment.
The concatenation techniques in this article, from simple + operations to the join() method, are the building blocks for real-world applications. With Replit Agent, you can transform these concepts into fully functional tools. For example, you could build:
- A unit converter that takes a number and outputs a formatted string like "100 kilometers is 62.137 miles."
- A dynamic status dashboard that displays real-time updates, such as "Server 3 has an uptime of 99 percent."
- A personalized message generator that combines user names with numerical data like scores or ages, perfect for a gaming leaderboard.
Describe your app idea and let Replit Agent write, test, and deploy the code for you, all within your browser.
Common errors and challenges
Even with the right tools, you might run into common pitfalls like type errors, unexpected None values, or performance bottlenecks during string concatenation.
Debugging TypeError when concatenating strings and integers
The most frequent issue is the TypeError, which Python raises when you try to use the + operator on a string and an integer. The error message is usually quite clear: TypeError: can only concatenate str (not "int") to str. This is your cue that an explicit conversion is needed.
- To fix this, find where you're adding a number to a string and wrap the numeric variable with the
str()function. - Alternatively, switch to an f-string or the
.format()method, as both automatically handle the conversion for you, making your code cleaner and less error-prone.
Handling None values in string formatting
Sometimes a variable might be None, and formatting it can lead to unintended results. Both f-strings and the str() function will convert a None value into the literal string "None". For instance, if a user's age is missing, your output might read "Age: None", which isn't very user-friendly.
- You can prevent this by checking for
Nonebefore formatting. - A more concise solution is to provide a fallback directly within an f-string, such as
f"Age: {age or 'N/A'}". This uses a short-circuit evaluation to display 'N/A' ifageisNone.
Avoiding performance issues with repeated string concatenation
Using the + operator to build a string piece by piece inside a loop is inefficient. Because Python strings are immutable, each concatenation creates a new string and copies the contents of the old ones. With many iterations, this process can significantly slow down your application.
- A far better approach is to append each string piece to a list.
- Once your loop is finished, use the
join()method to combine all the elements in the list into a single string. This method is highly optimized for this exact task, as it allocates memory only once.
Debugging TypeError when concatenating strings and integers
The TypeError is a classic stumbling block when joining different data types. It occurs when you use the + operator with a string and an integer, as Python can't guess whether you want to add or concatenate. The code below demonstrates this mistake.
name = "John"
age = 30
result = name + " is " + age + " years old."
print(result)
Here, the + operator tries to add the integer age to a string, which causes the error. Python can't mix types this way. The corrected code below demonstrates the proper approach to fix this.
name = "John"
age = 30
result = name + " is " + str(age) + " years old."
print(result)
The solution is to wrap the integer variable age with the str() function. This explicit conversion signals to Python that you want to treat the number as text, allowing the + operator to perform string concatenation correctly. You'll often encounter this TypeError when building dynamic strings from mixed data types, such as combining user input with static text. Always ensure your variables are strings before using the + operator for joining.
Handling None values in string formatting
When a variable is None, string formatting methods don't raise an error—they just convert it to the literal string 'None'. This often isn't the desired behavior, as it can lead to confusing or unprofessional output. The following code demonstrates this exact problem.
def get_user_data(user_id):
return {"name": "Alice", "age": None} if user_id else None
user = get_user_data(123)
message = f"{user['name']} is {user['age']} years old."
print(message) # Prints: Alice is None years old
The f-string directly inserts the value of user['age'], which is None, resulting in the literal string 'None' in the output. The corrected code below shows how to handle this gracefully.
def get_user_data(user_id):
return {"name": "Alice", "age": None} if user_id else None
user = get_user_data(123)
message = f"{user['name']} is {user['age'] if user['age'] is not None else 'unknown'} years old."
print(message) # Prints: Alice is unknown years old
The solution uses a conditional expression directly within the f-string. It checks if user['age'] is not None and provides a fallback string like 'unknown' if the value is missing. This prevents the literal string 'None' from appearing in your output. You'll find this technique useful when handling optional data from sources like APIs or database records, where some fields might not always be present.
Avoiding performance issues with repeated string concatenation
Using the + operator to build a string inside a loop is a common but inefficient practice. Since strings are immutable, each concatenation creates a new string, leading to significant slowdowns with many iterations. The code below demonstrates this performance trap.
numbers = list(range(1, 101))
result = ""
for num in numbers:
result += str(num) + ", "
print(f"Result starts with: {result[:20]}...")
In this loop, the += operator rebuilds the entire string with each of the 100 numbers. This constant memory reallocation is what causes the performance drag. The corrected code below demonstrates a much more optimized method.
numbers = list(range(1, 101))
result = ", ".join(str(num) for num in numbers)
print(f"Result starts with: {result[:20]}...")
The solution uses the join() method, which is highly optimized for this task. It first runs a generator expression, (str(num) for num in numbers), to convert each number to a string without creating an intermediate list in memory.
Then, join() efficiently combines all these strings into one. This approach avoids creating new strings in a loop, so it's much faster. You should use this method whenever you're building strings from many pieces, especially with large datasets.
Real-world applications
With these methods, you can move from fixing errors to building practical features like formatting currency values or generating simple CSV data.
Formatting currency values with str() and f-strings
Beyond simple concatenation, you can leverage f-strings to format numerical data into clean, readable currency values.
price = 1234.56
formatted_price = f"${price:,.2f}"
print(f"The product costs {formatted_price}")
prices = [9.99, 24.50, 4.99, 49.99]
total = sum(prices)
formatted_total = f"${total:.2f}"
print(f"Total: {formatted_total}")
This code showcases the power of f-string format specifiers for styling numbers. The expression f"${price:,.2f}" uses the section after the colon to control the output's appearance.
- The
,adds a thousands separator, making large numbers easier to read. - The
.2fformats the number as a float rounded to two decimal places.
The second example calculates a sum and applies similar formatting, showing how you can present calculated results cleanly. This technique is essential for creating professional-looking output from numerical data.
Building a simple CSV data formatter with join()
By nesting the join() method, you can efficiently transform a list of lists into a multi-line CSV string, a common task for exporting data.
def format_as_csv(data):
rows = []
for row in data:
csv_row = ",".join(str(item) for item in row)
rows.append(csv_row)
return "\n".join(rows)
employee_data = [
["Name", "Age", "Department", "Salary"],
["John Smith", 30, "Engineering", 85000],
["Lisa Jones", 28, "Marketing", 65000]
]
csv_output = format_as_csv(employee_data)
print(csv_output)
The format_as_csv function transforms a list of lists, like employee_data, into a single, multi-line string suitable for a CSV file. It processes the data structure in two main stages.
- First, it loops through each inner list, or row. A generator expression,
(str(item) for item in row), converts every item to a string before",".join()combines them with commas. - After creating a list of these comma-separated rows, the function uses
"\\n".join()to connect each row with a newline character, completing the CSV format.
Get started with Replit
Now, turn these concepts into a real tool. Describe what you want to build to Replit Agent, like “a tip calculator that outputs the total as a formatted string” or “a script that generates user activity logs.”
Our AI software engineer writes the code, tests for errors, and deploys your app. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)