While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python supports string concatenation using + operator. In most of the programming languages, if we concatenate a string with an integer or any other primitive data types, the language takes care of converting them to string and then concatenate it. However, in Python, if you try to concatenate string and int using + operator, you will get a runtime error.
Let’s look at a simple example to concatenate string and int using + operator.
s = 'Year is '
y = 2018
print(s + y)
Output:
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.
The easiest way is to convert int to a string using str() function.
print(s + str(y))
Output: Year is 2018
print("%s%s" % (s, y))
We can use string format() function too for concatenation of string and int.
print("{}{}".format(s, y))
If you are using Python 3.6 or higher versions, you can use f-strings too.
print(f'{s}{y}')
You can checkout complete python script and more Python examples from our GitHub Repository.
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Sign up
num = ([3,4,3,2,1]) print(reduce(lambda x,y: x * 10 + y ,num)) 34321
- Egmon
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
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
Hey Pankaj, thanks for sharing this article. This helped me to have a better understanding of formats used with print function
- Anupinder singh