Blog / Concatenating strings in Python

Concatenating strings in Python

by SW Team

String concatenation in Python

String concatenation is a very common operation in programming. In Python, there are several ways to perform string concatenation. The purpose of this blog is to explore different methods to concatenate strings in a Python program.

We can perform string joins in the following ways:

  1. Using the + operator.
  2. Using the join() method.
  3. Using the % operator.
  4. Using the format() function.
  5. Using f-string (string literal interpolation).

Concatenation of strings using the + operator

This is the simplest form of string concatenation. Let's look at a simple example.

s1 = 'SW'
s2 = 'Hosting'

s3 = s1 + s2

print(s3)

Exit:

SWHosting

cta:cloud_app_swpanel_smart_d5

It is very easy to use the + operator for string concatenation. However, the arguments must be of type string. For example, if we try to concatenate "Hello"+4, we will get the following error:

>>>'Hello' + 4
 Traceback (most recent call last):
  File "<input>", line 1, in 
TypeError: can only concatenate str (not "int") to str

To work around this, we can use the str() function to get the string representation of an object. Let's see how to concatenate a string with an Int or another object.

print('Hello' + str(7))

class Data:
    def __init__(self, i):
        self.id = i

    def __str__(self):
        return f'Data[{self.id}]'

print('Hello ' + str(Data(15)))

Exit:

Hello7
Hello Data[15]

In the first case, the script will print "Hello7" when concatenating the string "Hello" with the result of converting the number 7 into a string.

In the second case, by printing the result of str(Data(15)), you are converting the Data object with an identifier of 15 to a string representation. In Python, by defining the __str__ method within a class, you can customise the string representation of an object. In this case, calling str(Data(15)), invokes the __str__ method of the Data, class, which returns the string 'Data[15]'.

The main problem with the + operator is that we cannot add any separator or delimiter between strings. For example, if we have to concatenate "Hello" and "World" with a whitespace separator, we will have to write it as "Hello" + " " + "World".

cta:hosting

Concatenation of strings using the join() function

The join() function is useful for joining strings with a separator. It is especially handy when you have a sequence of strings, such as a list or a tuple of strings. If we do not want to use a separator, we can simply use the join() function with an empty string.

Example 1: Concatenation of strings using join ()
s1 = 'Hello'
s2 = 'World'

print(' Concatenation of strings using join () =', "".join([s1, s2]))
Example 2: Concatenation of strings using join() and spaces
s1 = 'Hello'
s2 = 'World'

print(' Concatenation of strings using join () and spaces =', " ".join([s1, s2]))

The result would be:

Concatenation of strings using join() = HelloWorld
Concatenation of strings using join() and spaces = Hello World

Concatenation of strings using the % operator

The % operator can be used for both string formatting and string concatenation. It comes in handy when we want to join strings together and perform simple formatting.

Example 1: Concatenation of strings using the % operator
s1 = 'Hello'
s2 = 'World'

s3 = "%s %s" % (s1, s2)
print('Concatenation of strings using the % operator =', s3)
Example 2: Concatenation of strings using the % operator with formatting
s1 = 'Hello'
s2 = 'World'

s3 = "%s %s from SWHosting - %d" % (s1, s2, 2024)
print('Concatenation of strings using the % operator with formatting =', s3)

The result would be:

Concatenation of strings using the % operator = Hello World
Concatenation of strings using the % operator with formatting = Hello World from SWHosting - 2024

Concatenation of strings using the format() function

The format() function is a powerful tool that offers flexibility in both string concatenation and formatting. Although it is important to remember that its use goes beyond simple string concatenation.

Example:
s1 = 'Hello'
s2 = 'World'

s3 = "{}-{}".format(s1, s2)
print('Concatenation of strings using format() =', s3)

s3 = "{in1} {in2}".format(in1=s1, in2=s2)
print('Concatenation of strings using format() =', s3)

Exit:

Concatenation of strings using format() = Hello-World
Concatenation of strings using format() = Hello World

Concatenation of Strings using f-string

If you are using Python 3.6 or later, you can also use f-string to concatenate strings. Here's a modern way to format strings.

s1 = 'Hello'
s2 = 'World'

s3 = f'{s1} {s2}'
print('Concatenation of strings using f-string =', s3)

product = 'iPhone'
price = 999.99
amount = 2

print(f'The product {product} has a price of {price} and the quantity available is { amount}')

Exit:

Concatenation of strings using f-string = Hello World
The iPhone product is priced at 999.99 and the available amount is 2

The Python f-string function is clearer and easier to write compared to the format() function. In addition, it automatically converts the object argument to a string when used as a field replacement.

Conclusion

There are multiple ways to format strings in Python. It is crucial to choose the most suitable one according to your requirements. For example, if you need to combine several strings with a separator, you can use the join() function. On the other hand, if you want to apply a specific format to the concatenation, it is advisable to use the format() function or the f-strings. It is essential to remember that f-strings are only compatible with Python 3.6 or later versions.

cta:cloud_so

i