Python Concatenate String and int
Let’s look at a simple example to concatenate string and int using + operator.
1 2 3 4 5 |
s="Year is " y = 2018 print(s + y) |
Output:
1 2 3 4 5 6 |
Traceback (most recent call last): File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module> print(s + y) TypeError: can only concatenate str (not "int") to str |
So how to concatenate string and int in Python? There are various other ways to perform this operation.
Using str() function
The easiest way is to convert int to a string using str() function.
1 2 3 |
print(s + str(y)) |
Output: Year is 2021
Using % Operator
1 2 3 |
print("%s%s" % (s, y)) |
Using format() function
We can use string format() function too for concatenation of string and int.
1 2 3 |
print("{}{}".format(s, y)) |
Using f-strings
If you are using Python 3.6 or higher versions, you can use f-strings too.
1 2 3 |
print(f'{s}{y}') |