In this tutorial, we will explore how to concatenate strings and integers in Python. Concatenating refers to the process of combining two strings or variables into one. It’s an essential coding task in Python especially because it makes the programming process easy and simplified. So, without further ado, let’s jump right into it.
Step 1: Concatenating Two Strings
Concatenating two strings in Python is as simple as using the “+” operator. You can do this as shown below:
1 2 3 4 |
str1 = "Hello" str2 = "World" str3 = str1 + " " + str2 print(str3) |
Output:
Hello World
Step 2: Converting Integer to String
In Python, you cannot concatenate a string with an integer directly. You need to convert the integer into a string first. You can achieve this by using Python’s built-in str() function. The str function converts a specified value into a string.
1 2 |
num = 123 print(str(num)) |
Output:
123
Step 3: Concatenating Strings and Integers
Now that you have the integer value as a string, you can concatenate it with a different string as shown below:
1 2 3 4 |
num = 123 str1 = "Hi" str2 = str1 + " " + str(num) print(str2) |
Output:
Hi 123
Full code:
Before proceeding to the conclusion, here is the complete code used in this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Concatenating Two Strings str1 = "Hello" str2 = "World" str3 = str1 + " " + str2 print(str3) # Converting Integer to String num = 123 print(str(num)) # Concatenating Strings and Integers num = 123 str1 = "Hi" str2 = str1 + " " + str(num) print(str2) |
Output:
Hello World 123 Hi 123
Conclusion
Concatenating strings and integers in Python is fairly simple and straightforward. Most operations in Python that involve a string and an integer require that the integer is converted into a string first. This is achieved using the in-built str() function.