5 easy ways to concatenate strings in Python with examples


Python

In this tutorial I will share different examples to concatenate stings in Python. You can choose either of the methods explained here but in case you have a long queue in some loop then you may want to choose wisely without impacting the performance.

 

I will be using following Python version to demonstrate all the examples:

 ~]# python3 -V
Python 3.6.8

 

Method-1: Concatenate strings using .format()

You can learn more about this method of formatting at 10+ simple examples to use Python string format in detail. Python 3.x uses a different formatting system, which is more powerful than the system that Python 2.x uses.

 

Example-1: Using default placeholders

You can just place open and closed curly braces {} where you want to place your string and using .format you can define the variables to be placed in the respective order.

#!/usr/bin/env python3

var1 = 'Python'
var2 = 'fun'

print('Let us learn {}, it is absolutely {}!'.format(var1, var2))

Here var1 and var2 will be added in the provided order i.e. first {} will be filled by var1 while the next {} will be filled by var2.

Output:

5 easy ways to concatenate strings in Python with examples

 

Example-2: Using positional arguments

Now the above example can be confusing when you have to concatenate multiple strings. So we can use positional arguments to define the position of each variable string.

#!/usr/bin/env python3

var1 = 'Python'
var2 = 'fun'

print('It is absolutely {1} to learn {0}!'.format(var1, var2))

Here we have defined the position {0} which will be for the first variable while {1} for the second variable.

Output:

5 easy ways to concatenate strings in Python with examples

 

Example-3: Using f-strings

Starting with Python 3.6 now we can use f-strings which is the recommended way of formatting strings. If you are familiar with the YAML concept of defining variables then it is almost similar where we place the variable name inside {} and then call the same inside f''. Following example will help you understand this more clearly:

#!/usr/bin/env python3

var1 = 'Python'
var2 = 'fun'

print(f'Let us learn {var1}, it is absolutely {var2}!')

Here if you notice <span style="color: #ffcc99;">f</span>'Let us learn {var1}, it is absolutely {var2}!' where we have defined the entire sentence under f'' while the individual variables are defined under {}. So this is much more cleaner and simpler compared to earlier format strings.

Output:

5 easy ways to concatenate strings in Python with examples

 

Method-2: Using + operator

In terms of performance, this method is most recommended to concatenate strings. Although you have to handle any extra spaces inside the string quotes. For example here I have two strings defined with separate variables.

 

Example-1: Concatenating strings

In this example we combine two strings using + operator.

#!/usr/bin/env python3

var1 = 'Python'
var2 = 'fun'

# I have handled extra whitespace under quotes and then
# concatenating strings using + operator
print('Let us learn ' + var1 + ', it is absolutely ' + var2 + '!')

If you observe, I have added an extra space 'Let us learn ' to handle the extra whitespace as + operate will concatenate the string in between the text but it will not add extra space unless the variable is defined in that way.

Output:

5 easy ways to concatenate strings in Python with examples

 

Example-2: Concatenating string with integers

Here I have a similar example but var2 is an integer instead of a string. So if we try to concatenate these two variables using + operator as we did earlier:

#!/usr/bin/env python3

var1 = 'Deepak'
var2 = 100

print('Hey ' + var1 + ', Can you lend me a ' + var2 + ' bucks?')

We are getting an TypeError "TypeError: must be str, not int" i.e. because + operator can only be used to concatenate strings. So we have to modify our code as following:

#!/usr/bin/env python3

var1 = 'Deepak'
var2 = 100

print('Hey ' + var1 + ', Can you lend me a ' + str(var2) + ' bucks?')

Now the script has run successfully:

5 easy ways to concatenate strings in Python with examples

 

Method-3: Append strings using += operator

If you are coming from shell script background then you must be familiar with += operator which is used in the same way as used with shell i.e. to append or add content to existing variable. This is another recommended method to concatenate strings with less performance impact.

 

Example-1: Join two block of sentences

In this example I have two variables with strings and I want to join both these strings. So I am using += operator to add the content of var2 with a whitespace in var1 variable.

#!/usr/bin/env python3

var1 = 'First block of sentence.'
var2 = 'Second block of sentence.'

# Append extra whitespace and var2 into var1
var1 += ' ' + var2
print(var1)

Output:

5 easy ways to concatenate strings in Python with examples

 

Example-2: Using for loop

This scenario would make more sense and will be used more often. Here we have taken a simple example where we iterate over a range value of 5 and then append each digit into our variable str1

#!/usr/bin/env python3

# Define variable with empty string value
str1 = ''

for i in range(5):
   # append strings to the variable
   str1 += str(i)

# print variable str1 content
print(str1)

Output:

5 easy ways to concatenate strings in Python with examples

 

Method-4: Concatenate strings using .join()

We can also use str.join() method to join two strings using a delimiter. The join() method is called on a string, gets passed a list of strings, and returns a string. A TypeError will be raised if there are any non-string values in iterable, including bytes objects.

#!/usr/bin/env python3

var1 = 'First block of sentence'
var2 = 'Second block of sentence'

# Join both var1 and var2 using fullstop
# as the separator
out = ". ".join((var1, var2))
print(out)

# Join both var1 and var2 using comma
# as the separator
out = ", ".join((var1, var2))
print(out)

Output:

5 easy ways to concatenate strings in Python with examples

 

Method-5: Concatenate strings using % operator

We must NOTE that % string operator is deprecated and will be removed in higher Python release so I would recommend you to use other methods which I have explained in this tutorial for string concatenation. For the sake of reference I will share an example to use % operator:

#!/usr/bin/env python3

var1 = 'Python'
var2 = 'fun'

# Combining strings using % operator
print('Let us learn %s, it is absolutely %s!' % (var1, var2))

Here %s will be replaced by the mapping string which we have shared with % (var1, var2).

Output:

5 easy ways to concatenate strings in Python with examples

 

Summary

In this Python tutorial we learned about different methods using which we can concatenate strings. I have shared multiple examples for individual methods which can help you understand the basics so you can implement them accordingly in your code. You can also follow stackoverflow forum where this topic is discussed in depth in terms of performance impact for different methods and the recommended ones.

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment