Python supports string concatenation using the +
operator. In most other programming languages, if we concatenate a string with an integer (or any other primitive data types), the language takes care of converting them to a string and then concatenates it.
However, in Python, if you try to concatenate a string with an integer using the +
operator, you will get a runtime error.
Let’s look at an example for concatenating a string (str
) and an integer (int
) using the +
operator.
current_year_message = 'Year is '
current_year = 2018
print(current_year_message + current_year)
The desired output is the string: Year is 2018
. However, when we run this code we get the following runtime error:
Traceback (most recent call last):
File "/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
print(current_year_message + current_year)
TypeError: can only concatenate str (not "int") to str
So how do you concatenate str
and int
in Python? There are various other ways to perform this operation.
In order to complete this tutorial, you will need:
This tutorial was tested with Python 3.9.6.
str()
FunctionWe can pass an int
to the str()
function it will be converted to a str
:
print(current_year_message + str(current_year))
The current_year
integer is returned as a string: Year is 2018
.
%
Interpolation OperatorWe can pass values to a conversion specification with printf-style String Formatting:
print("%s%s" % (current_year_message, current_year))
The current_year
integer is interpolated to a string: Year is 2018
.
str.format()
functionWe can also use the str.format()
function for concatenation of string and integer.
print("{}{}".format(current_year_message, current_year))
The current_year
integer is type coerced to a string: Year is 2018
.
If you are using Python 3.6 or higher versions, you can use f-strings, too.
print(f'{current_year_message}{current_year}')
The current_year
integer is interpolated to a string: Year is 2018
.
In web applications, it’s common to display dynamic content to users, such as the number of new messages they have. By concatenating strings and integers, you can dynamically generate messages like “You have X new messages” where X is the actual number of new messages.
Example:
new_messages_count = 5
message = "You have " + str(new_messages_count) + " new messages"
print(message) # Output: You have 5 new messages
When creating log messages or reports, you often need to include specific data, such as dates, times, or numerical values. Concatenating strings and integers allows you to dynamically generate these messages with the correct information.
Example:
log_message = "Error occurred at timestamp: " + str(timestamp) + " with error code: " + str(error_code)
print(log_message) # Example output: Error occurred at timestamp: 1643723400 with error code: 500
In various applications, you might need to generate file names or database entries dynamically. For example, you might want to save a file with a name that includes a timestamp or a unique identifier. By concatenating strings and integers, you can dynamically generate these file names or database entries with the required information.
Example:
file_name = "log_" + str(timestamp) + ".txt"
print(file_name) # Example output: log_1643723400.txt
This error occurs when you try to concatenate a string with an integer using the +
operator. To fix this, you need to convert the integer to a string using the str()
function.
Example:
current_year_message = 'Year is '
current_year = 2018
print(current_year_message + str(current_year)) # Corrected output: Year is 2018
str()
When concatenating strings and integers, it’s essential to convert the integer to a string using str()
. Failing to do so will result in a TypeError.
Example:
new_messages_count = 5
message = "You have " + str(new_messages_count) + " new messages"
print(message) # Corrected output: You have 5 new messages
+
vs ,
in print()
In Python, when using print()
, you can use either the +
operator for string concatenation or the ,
operator for separating arguments. However, using +
with integers will raise a TypeError. To fix this, use the ,
operator to separate arguments, which will automatically convert integers to strings.
Example:
print("You have", 5, "new messages") # Corrected output: You have 5 new messages
Method | Example | Pros | Cons |
---|---|---|---|
+ Operator |
print("Year is " + str(2018)) |
Simple to use, easy to understand | TypeError if not converted to string, less efficient for large strings |
str() Function |
print("Year is " + str(2018)) |
Explicit conversion, easy to use | Extra step required, less efficient for large strings |
% Interpolation |
print("%s%s" % ("Year is ", 2018)) |
Legacy support, simple to use | Less readable, less flexible, less efficient, deprecated in Python 3.x |
str.format() |
print("{}{}".format("Year is ", 2018)) |
Flexible, readable, supports multiple arguments | More verbose, less efficient for simple cases |
f-strings | print(f"Year is {2018}") |
Most readable, flexible, efficient | Python 3.6+ only, not suitable for older Python versions |
, Operator |
print("Year is", 2018) |
Simple, readable, easy to use | Only for print() function, not suitable for string concatenation in general |
After evaluating the pros and cons of each method, it is clear that f-strings are the best method for concatenating strings and integers in Python. They are the most readable and flexible, and are supported in Python 3.6 and higher.
In Python, you cannot directly concatenate a string and an integer using the +
operator because they are different data types. Python is a statically typed language, which means it checks the data type of variables at runtime. When you try to concatenate a string and an integer, Python throws a TypeError because it cannot implicitly convert the integer to a string.
Example:
# This will raise a TypeError
print("Year is " + 2018)
To fix this error, you need to convert the integer to a string using the str()
function or f-strings. This allows Python to concatenate the string and the integer as strings.
Example:
# Corrected using str()
print("Year is " + str(2018))
# Corrected using f-strings
print(f"Year is {2018}")
The best way to concatenate strings and numbers in Python is to use f-strings. They are the most readable, flexible, and efficient method, especially for Python 3.6 and higher. F-strings allow you to embed expressions inside string literals, using curly braces {}
.
Example:
# Using f-strings
print(f"Year is {2018}")
It depends on the Python version you are using and personal preference. For Python 3.6 and higher, f-strings are the recommended method due to their readability and flexibility. For older Python versions, using str()
or the %
interpolation method might be necessary.
Example:
# Using str() for older Python versions
print("Year is " + str(2018))
# Using % interpolation for older Python versions
print("Year is %s" % 2018)
F-strings work by embedding expressions inside string literals using curly braces {}
. The expressions are evaluated and converted to strings, then inserted into the string at the corresponding position. This allows for dynamic string creation with embedded values.
Example:
# Embedding an expression in an f-string
current_year = 2018
print(f"Year is {current_year}") # Output: Year is 2018
In conclusion, mastering string concatenation and manipulation is a crucial aspect of Python programming. By understanding the different methods of concatenating strings and numbers, including using the +
operator, str()
function, and f-strings, you can effectively create dynamic strings and improve the readability of your code. Additionally, learning about list concatenation, joining lists, and string functions can further enhance your skills in working with strings and lists in Python. For more in-depth tutorials on these topics, refer to the following resources:
These tutorials will provide you with a comprehensive understanding of working with strings and lists in Python.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Hey Pankaj, thanks for sharing this article. This helped me to have a better understanding of formats used with print function
- Anupinder singh
Write a python program that asks the user how many coins of various types they have, and then prints the total amount of money in rupees.
- M P ANUPAMA
it works fine but takes too much time for instance if we have to convert integer to string 200 times , you would be able to notice the time taken to execute the code. How can we deal with that to make our code more efficient?
- future googler
num = ([3,4,3,2,1]) print(reduce(lambda x,y: x * 10 + y ,num)) 34321
- Egmon