DevOps | Scripts | Automation

Python

How to concatenate strings in Python?

a. Concat String with ‘+’ Operator

In Python concatenating strings are easy. For example, let’s say you have two strings to merge then you put the plus (‘+’) operator to merge two strings.

str1 = "Hello"
str2 = "World"

str = str1 + ' ' + str2

print(str)

The output will be “Hello World“. If you have more strings then just add more operators to merge the strings.

b. Concat string with Join function

Another way to merge the string is by using the Join() function of the string. For example,

str1 = "Hello"
str2 = "Python"
str3 = "World"

str = ' '.join([str1,str2,str3])

print(str)

The output will be “Hello Python World“.

In the Join function, we are providing strings to concate and the separator before joining. Here, space is the separator.

Join() function is the standard way to merge strings. You can also provide a list or tuple as an input.


b.1 Concat List

list = ["Dog","Cat","Cow"]
str = ' '.join(list)
print(str)

The output will be “Dog Cat Cow“.


b.2 Concat tuple

wild_animals = ('Tiger','Lion','Fox')
str = ' '.join(wild_animals)
print(str)

The output will be “Tiger Lion Fox“.

It’s easy to merge strings when you use the Join() function.

You can get all the code above from the GitHub repo below.

https://github.com/chiragce17/MyPublicRepo/blob/main/Python/Scripts/ConcateStrings.py

Loading