Introduction
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.
Example
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.
Prerequisites
In order to complete this tutorial, you will need:
- Familiarity with installing Python 3. And familiarity with coding in Python. How to Code in Python 3 series or using VS Code for Python.
This tutorial was tested with Python 3.9.6.
Using the str()
Function
We 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
.
Using the %
Interpolation Operator
We 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
.
Using the str.format()
function
We 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
.
Using f-strings
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
.
Conclusion
You can check out the complete Python script and more Python examples from our GitHub repository.
Source:
https://www.digitalocean.com/community/tutorials/python-concatenate-string-and-int