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

In this code, a variable called str1 is initialized with the string value ‘Hello’. Then another variable str2 is initialized with the value ‘Stechies’. A variable str3 is assigned an empty string. In the next statement, the variable str3 is assigned the concatenated value of the three string variables. The + operator is used for adding them together. The last line of code, print('Final String: ', str3)  prints out the final value of the variable str3.

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

The first line initializes a variable called str1 with the value ‘Hello’. The str2 variable is assigned the value ‘Stechies’ and str3 is initialized with an empty string. The next print() method print('Final String: ', '' .join([str1, str3, str2])), prints the three strings with the join method with a space character. Next, these strings are again joined together with the help of the join method. The final value is assigned to a variable called final_string. The last line prints the value of this variable along with the string “Final String with variable: ”.

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

Here, two variables str1 and str2 are initialized with the values ‘Hello’ and ‘Stechies’ respectively. An empty string is assigned to the variable called str3. The last line of the code is:

print("Final String: {}{}{}".format(str1, str3, str2))

Here, the print() method is used for printing out the combination of the three string values. The format() method secures the placeholder for the strings with the help of the curly braces {} {} {}. As a result, ‘Hello’, ‘Stechies’ and ‘ ’ are printed consecutively.

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

The first line initializes a variable called str1 with the value ‘Hello’. The str2 variable is assigned the value ‘Stechies’ and str3 is initialized with an empty string. In the next line print(f'{str1} our site is {str2}') the stings are joined with other strings. Here, strings str1 and str2 are combined with the strings “our site is”. The next line of code joins the three strings str1 str3 and str2 with the f - string method.

The value is then assigned to a variable called final_string. The value of this variable is printed by a print() statement in the last line of the program.

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

Here, a variable called list1 is initialized with the list elements ['Our ', 'Site ', 'is ', 'stechies.com']. An empty string is assigned to the variable final_string. Then in a for loop, a variable l1 is used for iterating over the list1. All the elements of the list1 are added to the final_string variable. The value of the final_string is printed in the last line. 

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

In this code, the variables str1, str2, str4 and str5 are all initialized with values - str1 = 'Hello', str2 = 'I am', str4 = 'years' and str5 = 'old'. The variable str3 is assigned the integer value 25. The string values of all these variables are added using the concatenation operator +. The final value is stored in the str3 variable.

The last line of the program prints the string “Final string” and str3 variable value. After code execution, en error is encountered. This occurs as the code tries to add the strings and the integer value together, which is not possible. 

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.