Online Tutorials & Training Materials | STechies.com
Register Login

Python String Concatenation - 4 Methods of With Examples

23 Sep 2019 12:38 pm || 0

Multiple operations can be performed in Python. You can remove a substring from a string, slice a part of the string, run a for loop over the characters of the string. You can also join two or more strings. When we join two or more string in one string with the help of operators or functions, this process known as String Concatenation.

In python, we can join two strings in multiple ways.

For example, we have two strings here one is “Hello” and another one is“STechies” we will use different methods to join these two strings into one string which is“Hello STechies”.

In Python, string concatenation can be done using different ways:

1. Using + Operator
2. Using Join() Method
3. Using { } Operators
4. Using f-string (Literal String Interpolation)

1. Using + Operator

The most common method to perform string concatenation is by using “+” operator, in this we need to just concatenate two string with + operator.

Example

# Python program to explain String Concatenation Using "+" Operator

# Declare strings
str1 = 'Hello'
str2 = 'Stechies'
str3 = ' '

# Concatenation strings with "+" operator
str3 = str1+str3+str2

# Print output
print('Final String: ', str3)

Output

Final String: Hello Stechies

Explanation

Let us try to understand the code written above. Here, the main concatenation happens inside the variable str3, in the statementstr3 = str1+str3+str2. If just the first two variables str1 and str2 were added using the + operator, the result would have been “HelloStechies”. But as thestr3variable is assigned an empty string, it creates a space in between the two variables when it is added between str1 and str2. The final result is thus “Hello Stechies”.

2. Using Join() Method

Let us now see how we can concatenate strings without using the + operator. We can use a method called join() in this case.

The join() method is used for joining or concatenating two or more strings. This method works by joining the sequence of strings with the separator mentioned by the user. The syntax of join() is:

str.join(sequence)

Here, the str is the separator that will be used to combine the sequence of strings. Let us look at an example.

Example

# Python program to explain string concatenation using join method

# Declare strings
str1 = 'Hello'
str2 = 'Stechies'
str3 = ' '

# Join strings and print output
print('Final String: ', '' .join([str1, str3, str2]))

# Join String and get output in variable
final_string = ''.join([str1, str3, str2])

# Join strings and print output
print('Final String with variable: ', final_string)

Output

Final String: Hello Stechies
Final String with variable: Hello Stechies

Explanation

In this program, the join() method is used for concatenating the three strings. In the statementfinal_string = ''.join([str1, str3, str2]), the ‘ ’ is the space character provided to the join() method for concatenating the strings str1, str2 and str3. So, according to the syntax of join() mentioned earlier, ‘ ’ is the strand the sequence consists of the three string variables str1, str2 and str3. Thus, the method joins the strings together with space in between.

The resultant string is “Hello Stechies”.

3. Using String Formatting with the { } Operators

Format function with curly braces is used commonly for concatenation. This is because when we use {}, it reserves the placeholder for the variable. The format() function passes the variable to the {} operator.

For integer values, it is not necessary to convert an integer into a string for concatenation.

Example

# Python program to explain string concatenation using curly braces or {} operator 

# Declare strings
str1 = 'Hello'
str2 = 'Stechies'
str3 = ' '

# Join strings and print string using curly braces or {}
print("Final String: {}{}{}".format(str1, str3, str2))

Output

Final String: Hello Stechies

Explanation

The actual concatenation occurs in the code statement print("Final String: {}{}{}".format(str1, str3, str2)). Here, the curly braces are placeholders. These represent the three string variables str1, str2 and str3; having values ‘Hello’, ‘Stechies’ and ‘ ’ respectively. As the placeholders are empty, Python will replace the values passed within the format() method according to the order they are passed.

Thus, ‘Hello’, ‘Stechies’ and ‘ ’ are printed consecutively. We can see that there are no spaces between the curly braces. So the final output is Hello Stechies, where the empty string assigned to the variable str3 creates the space in between the two words.

4. Using f-string

The f-string is an advanced function that is actually known as Literal String Interpolation. It provides a fast and efficient way to format strings using placeholders. It works like the format() method but here you can mention the names of the variables inside the curly braces or placeholders.

It works with Python 3.6+ versions.

Example

# Python program to explain string concatenation using f-string

# Declare strings
str1 = 'Hello'
str2 = 'Stechies'
str3 = ' '

# Join strings and print string using f-string
print(f'{str1} our site is {str2}')

# pass concatenation value in in varaible
final_string = f'{str1}{str3}{str2}'

# Print variable
print(final_string)

Output

Hello Our site is Stechies
Hello Stechies

Explanation

Let us understand the concatenation in the fourth line of the code,print(f'{str1} our site is {str2}'). Here, the variables str1 and str2 are mentioned inside the curly braces. While printing out the result, the variables are replaced by their values. The result of this print statement is“Hello our site is Stechies”. Then in the line final_string = f'{str1}{str3}{str2}', the f-string function is used for mentioning the three variables str1, str2 and str3 within the curly braces. They are substituted by their values while printing.

Therefore, the final value of the variable final_string is“Hello Stechies”.

Concatenate String Using Native Function

Example

# Python program to explain String Concatenation using for loop by append string in loop

# Inilised a list
list1 = ['Our ', 'Site ', 'is ', 'stechies.com']

# Inilised string variable 
final_string = ''

# Append string in loop
for l1 in list1:
    final_string += l1
    
# print output
print(final_string)

Output

Our Site is stechies.com

Explanation

Inside the for loop, the variable l1 iterates through the list elements of list1. After each iteration, it adds each element to the variable final_string, which is initialized with an empty string. For example, after the first iteration, the final_string variable has the value of “Our”. Then in the next iteration, the string “Site” is added to the variable, making the variable value “Our Site”. Similarly, the other strings are added to the final_string variable. This method is easy to use while working with lists.

The final result is “Our Site is stechies.com”.

Concatenate String and Integer Variable

To concatenate string and integer variable, you need to convert integer variable to string and then concatenate using ‘+’ operator.

Example

# Python program to explain String Concatenation Using "+" Operator

# Declare strings & Integer varaibles
str1 = 'Hello'
str2 = 'I am'
str3 = 25
str4 = 'years'
str5 = 'old'


# Concatenation strings with "+" operator
str3 = str1+' '+str2+' '+str3+' '+str4+' '+str5

# Print output
print('Final String: ', str3)

Output

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    str3 = str1+' '+str2+' '+str3+' '+str4+' '+str5
TypeError: Can't convert 'int' object to str implicitly

Explanation of Error

The error is encountered because concatenation is not possible between variables of different data types. As the variables str1, str2, str4 and str5 are assigned string values and the variable str3 has an integer value, they cannot be added. Therefore, the statementstr3 = str1+' '+str2+' '+str3+' '+str4+' '+str5throws an error.

Correct Example

# Python program to explain String Concatenation Using "+" Operator

# Declare strings & Integer variables
str1 = 'Hello'
str2 = 'I am'
str3 = 25
str4 = 'years'
str5 = 'old'

# Concatenation strings with "+" operator
str3 = str1+' '+str2+' '+str(str3)+' '+str4+' '+str5

# Print output
print('Final String: ', str3)

Output

Final String: Hello I am 25 years old

Explanation

The code here runs smoothly without any errors. This is because the string variables are added together along with the integer – which is converted to a string. The integer value in str3 is converted to a string using the str() method. Then this string value is concatenated with the other strings using the + operator.

The error encountered before is avoided here as the two variables are of the same data type.

Conclusion

Adding or combining string values using the + operator is very efficient. But you may have a long and complicated string, in which you need to insert other string values. Using the format() method and f-string method will be faster and efficient here. But make sure you are concatenating the values of the same type. If the values are not homogeneous, convert them using int() or str() methods for avoiding TypeErrors during program execution.