One common task you’ll need to accomplish with any language involves merging or combining strings. This process is referred to as string concatenation. This post will describe string concatenation in Python. There are different ways to do that, and we will discuss the most common methods. After, we will explore formatting, and how it works.
What is String Concatenation in Python?
When we combine two or more strings in Python, the operation is called string concatenation.
In Python, there are many ways to concatenate or combine two or more strings. When we concatenate two or more strings, the new string is stored in a new string object. Obviously, this is because everything in Python is an object – which is why Python is an objected-oriented language.
In order to merge two strings into a single object, you may use the “+” operator. When writing code, that would look like this:
str1="Python"
str2="ForBeginners"
print("The first string is:",str1)
print("The second string is:",str2)
newStr=str1+str2
print("The concatenated string is:",newStr)
Output:
The first string is: Python
The second string is: ForBeginners
The concatenated string is: PythonForBeginners
In the above code, we have created two string objects str1 and str2. Then, we used the + operator to concatenate both strings. You can also concatenate more than two strings using the + operator as long as all the operands are valid strings. For instance, you can concatenate three strings in Python as shown below.
str1="Python"
str2="For"
str3="Beginners"
print("The first string is:",str1)
print("The second string is:",str2)
print("The third string is:",str3)
newStr=str1+str2+str3
print("The concatenated string is:",newStr)
Output:
The first string is: Python
The second string is: For
The third string is: Beginners
The concatenated string is: PythonForBeginners
Concatenate String and Integer in Python
Python doesn’t support concatenating a string and an integer. These are considered two separate types of objects. If you try to concatenate a string and an integer, the program will run into a Python TypeError exception as shown below.
myStr="PythonForBeginners"
myInt=1117
print("The string is:",myStr)
print("The integer is:",myInt)
newStr=myStr+myInt
print("The concatenated string is:",newStr)
Output:
The string is: PythonForBeginners
The integer is: 1117
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_56401/527270139.py in <module>
3 print("The string is:",myStr)
4 print("The integer is:",myInt)
----> 5 newStr=myStr+myInt
6 print("The concatenated string is:",newStr)
TypeError: can only concatenate str (not "int") to str
In the above output, you can observe that we have tried to concatenate the string “PythonForBeginners” and the integer 1117. Due to this, the program runs into a TypeError exception.
If you still want to merge a string and an integer, you will need to convert the integer to a string. Then, you can perform string concatenation on the two Python strings as shown below.
myStr="PythonForBeginners"
myInt=1117
print("The string is:",myStr)
print("The integer is:",myInt)
newStr=myStr+str(myInt)
print("The concatenated string is:",newStr)
Output:
The string is: PythonForBeginners
The integer is: 1117
The concatenated string is: PythonForBeginners1117
In this example, we first converted the integer 1117 to a string using the str() function. Then, we concatenated the strings using the + operator. Hence, the program executes successfully and we get the output.
Multiply String By a Number in Python
When we multiply a string with an integer N, the string is repeated N times and we get a new string object. You can observe this in the following example.
myStr="PythonForBeginners"
N=3
print("The string is:",myStr)
print("The number is:",N)
newStr=myStr*N
print("The output string is:",newStr)
Output:
The string is: PythonForBeginners
The number is: 3
The output string is: PythonForBeginnersPythonForBeginnersPythonForBeginners
In the above code, we have multiplied the original string by 3. Hence, we get a new string with the original string repeated three times.
If you multiply a string by 0, you will get an empty string as shown below.
myStr="PythonForBeginners"
N=0
print("The string is:",myStr)
print("The number is:",N)
newStr=myStr*N
print("The output string is:",newStr)
Output:
The string is: PythonForBeginners
The number is: 0
The output string is:
In the above code, we have multiplied the original string with 0. Hence, we get an empty string in the output. Even if you multiply a string with a negative integer, you will get an empty string in the output.
You cannot multiply a string with a floating point number. In this case, the program will run into a TypeError exception as shown in the following example.
myStr="PythonForBeginners"
N=3.5
print("The string is:",myStr)
print("The number is:",N)
newStr=myStr*N
print("The output string is:",newStr)
Output:
The string is: PythonForBeginners
The number is: 3.5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_56401/1345002117.py in <module>
3 print("The string is:",myStr)
4 print("The number is:",N)
----> 5 newStr=myStr*N
6 print("The output string is:",newStr)
TypeError: can't multiply sequence by non-int of type 'float'
In the above code, we have tried to multiply a string by 3.5. As 3.5 is a floating point number, you can observe that the program runs into a TypeError exception saying that we cannot multiply a sequence by a non-int type of float.
String Concatenation Using The join() Method
If you want to concatenate the strings separated by a string or character as a separator, you can use the join() method. The join() method, when invoked on a separator string, takes a list of strings as its input argument. After execution, it concatenates all the strings in the list by the separator and returns a new string. You can observe this in the following example.
str1="Python"
str2="For"
str3="Beginners"
print("The first string is:",str1)
print("The second string is:",str2)
print("The third string is:",str3)
newStr=" ".join([str1,str2,str3])
print("The concatenated string is:",newStr)
Output:
The first string is: Python
The second string is: For
The third string is: Beginners
The concatenated string is: Python For Beginners
In the above example, we have concatenated three strings using the space character. For this, we invoked the join() method on a string containing the space character and passed a list of all the input strings. After execution of the join() method, we get the desired output.
Suggested reading: String Manipulation
String Formatting in Python
In Python, we can format strings using string interpolation in three different ways.
String interpolation is a term used to describe the process of evaluating a string value that is contained as one or more placeholders. To put it simply, it helps developers with string formatting and concatenation. Hopefully, you are more familiar with the term yourself because it’s a crucial element of any programming language, especially Python.
We can perform string formatting using the following ways.
- The % operator.
- Using f-strings
- The format() method
Let us discuss all three ways one by one.
Formatting Strings Using the % Operator in Python
The % operator uses format specifiers of values as placeholders for string formatting. When invoked on a string, the % operator takes a variable or tuple of variables as input and places the variables in the specified format specifiers in the string. To understand this, consider the following example.
x = "mangoes"
y = 15
z = "The number of %s in the basket is %d." % (x,y)
print(z)
Output:
The number of mangoes in the basket is 15.
In the above example, we have inserted an integer and a string value into the string “The number of %s in the basket is %d.” using the ‘% operator. Here, %s and %d is the format specifier for string and integer respectively. The other format specifiers are %f for float, %c for character, and %e for floating point exponential.
The variables in the tuple on the right side of the % operator contain values that are inserted into the strings. Here, the data type of the values in the variables should be in the same order as the data type defined by the format specifiers. Otherwise, the program will run into error.
x = "mangoes"
y = 15
z = "The number of %s in the basket is %d." % (y,x)
print(z)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_6318/3859633640.py in <module>
1 x = "mangoes"
2 y = 15
----> 3 z = "The number of %s in the basket is %d." % (y,x)
4 print(z)
TypeError: %d format: a real number is required, not str
In the above code, we have passed the integer value as the first element and the string value as the second element in the tuple passed to the % operator. In the string, the first format specifier expects a string and the second format specifier expects an integer. Due to this, the program runs into a TypeError exception.
In the above code, you also need to understand that the values passed in the tuple must be equal to the number of format specifiers in the string. Otherwise, the program will run into an error saying that there are not enough arguments for the format string. You can observe this in the following example.
x = "mangoes"
y = 15
z = "The number of %s in %d baskets is %d." % (x,y)
print(z)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_6318/270842158.py in <module>
1 x = "mangoes"
2 y = 15
----> 3 z = "The number of %s in %d baskets is %d." % (x,y)
4 print(z)
TypeError: not enough arguments for format string
In this example, there are three format specifiers in the string. However, we have passed only two values to the % operator. Hence, the program runs into error.
If we pass more input arguments than the format specifiers in the string, the program again runs into a TypeError exception saying not all arguments are converted during string formatting as shown below.
x = "mangoes"
y = 15
z = "The number of %s in %d baskets is %d." % (x,y,1117,"PFB")
print(z)
Output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_6318/120037793.py in <module>
1 x = "mangoes"
2 y = 15
----> 3 z = "The number of %s in %d baskets is %d." % (x,y,1117,"PFB")
4 print(z)
TypeError: not all arguments converted during string formatting
In this example, there are three format specifiers in the string. However, we passed four values as input to the % operator. Hence, the program runs into error.
Format String Using f-strings in Python
As the name suggests, f-strings are used for formatting strings. In f-strings, you can directly pass the variable name inside curly braces. After execution of the statement, the values in the variable are interpolated in the actual string. You can observe this in the following example.
x = "mangoes"
y = 15
c=1117
z = f"The number of {x} in {y} baskets is {c}."
print(z)
Output:
The number of mangoes in 15 baskets is 1117.
Here, you can observe that we passed the variable names directly to the curly braces in the f-string. Using f-strings has the benefit that you don’t need to care about the order of variables passed to the strings as each variable is passed to the string using its name.
String Formatting Using the format() Method in Python
Instead of the % operator, you can use the format() method for string formatting in Python. In this case, we use curly braces {} instead of the format specifiers for placeholders. When we invoke the format() method on the string containing placeholders, we can pass the values as input arguments to the format() method. After execution of the statement, we get the formatted string. You can observe this in the following example.
x = "mangoes"
y = 15
z = "The number of {} in {} baskets is {}.".format(x,y,1117)
print(z)
Output:
The number of mangoes in 15 baskets is 1117.
While using the format() method for string formatting, if you pass more values to the format() method than the placeholders in the string, the program doesn’t run into an error. However, if you pass fewer values than the placeholders in the string. The program will run into errors.
One benefit of using the format() method is that you do not have to convert integers into a string before concatenating the data. It will do that automatically for you. This is one reason why it is the preferred operator method.
Another useful feature of the format() method is that you don’t actually have to feed the inputs to the interpreter in the same order that you want the variables to be displayed, as long as you specify the indices of the values in the placeholders. For example, you can put the position of the input values in the placeholders and pass the values to the format() method as shown below.
x = "mangoes"
y = 15
z = "The number of {0} in {2} baskets is {1}.".format(x,1117,y)
print(z)
Output:
The number of mangoes in 15 baskets is 1117.
In this output, you can observe that we have numbered the placeholders. Hence, the values are assigned to the placeholders according to the index number and not the actual order of the format specifiers in the string. The value 1117 is still assigned to the third placeholder even after giving it as a second input argument to the format() method. This is due to the reason that the third placeholder contains index 1.
Instead of the indices, you can also name the placeholders and pass the values as key-value pairs to the format() method as shown below.
x = "mangoes"
y = 15
z = "The number of {a} in {b} baskets is {c}.".format(a=x,c=1117,b=y)
print(z)
Output:
The number of mangoes in 15 baskets is 1117.
In this example, we named the placeholders a,b, and c. Then, we assign the values to the names while passing them to the format() method. You can observe that the values are assigned to the placeholders according to their names.
Conclusion
In this article, we discussed string concatenation and formatting in Python. To learn more about Python programming, you can read this article on Python Strings. You might also like this article on Reversing Lists and Strings.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.