Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to concatenate a string with numbers in Python?
Concatenation is the process of joining two or more strings together. In Python, you cannot directly concatenate a string with a number using the '+' operator, as it raises a TypeError due to incompatible data types.
Python does not allow implicit conversion between strings and numbers during concatenation. Therefore, we need to explicitly convert numbers to strings before joining them.
Using str() Function
The str() function converts any value into a string representation. This is the most straightforward approach for string-number concatenation.
Syntax
str(x)
Example
Here's how to use the str() function to concatenate a string with a number ?
name = "TutorialsPoint_" year = 2025 result = name + str(year) print(result)
TutorialsPoint_2025
Using format() Method
The format() method replaces placeholders {} in a string with corresponding values, automatically handling type conversion.
Syntax
str.format(value1, value2, ...)
Example
Using format() method to concatenate strings with numbers ?
notifications = 6
result = "You have {} notifications".format(notifications)
print(result)
You have 6 notifications
Using f-strings (Formatted String Literals)
F-strings provide the most readable and efficient way to format strings in Python 3.6+. They are created by prefixing a string with 'f' or 'F' and placing expressions inside curly braces {}.
F-strings were introduced in Python 3.6. For earlier versions, use the format() method.
Example
Using f-strings for clean and readable concatenation ?
website = "Welcome_To_"
year = 2025
result = f"{website}{year}"
print("The concatenated string is:")
print(result)
The concatenated string is: Welcome_To_2025
Using % Operator (String Formatting)
The % operator provides C-style string formatting. Use %s as a placeholder for each value, then specify the values in a tuple after the % operator.
Example
Using the % operator for string concatenation ?
car_model = "Chevrolet_Camaro_"
year = 2025
result = "%s%s" % (car_model, year)
print("The concatenated string is:")
print(result)
The concatenated string is: Chevrolet_Camaro_2025
Comparison
| Method | Python Version | Performance | Readability |
|---|---|---|---|
str() |
All versions | Good | Basic |
format() |
2.7+ | Good | Very good |
f-strings |
3.6+ | Best | Excellent |
% operator |
All versions | Fair | Fair |
Conclusion
F-strings offer the best combination of performance and readability for Python 3.6+. For older versions, use format() for complex formatting or str() for simple concatenation.
