Thursday, September 12, 2019

Python Concatenate Strings | With Examples

What is concatenation?

Usually in any programming language, string concatenation means to join 2 strings together.  For example, if we have string1 = “Learn” and string2 = “Python”. The concatenation of string1 and string2 will give a result “Learn Python”. The contents of both items are merged by placing them side by side.

In this post we will learn how to do concatenation in python. In python strings are str objects. String objects are immutable.

Concatenation using ‘+’ Operator

This is the quickest way in Python to concatenate strings. You simply need to put ‘+’ in between various string variables and get a combined string as a result.

Example 1:


”Hello” + “ World” + “ !!” 
Output

“Hello World !!”

Note that spaces were included as part of string.

Example 2:


"help” * 5

Output

“helphelphelphelphelp”

This is another unique feature of Python. You can multiply a string and concatenate it as many times as you want.

Example 3:


str1 = “Learn”
str2 = “ Python”
str1 + str2

Output

“Learn Python”


str3 = str1 + str2
Print str3

Output

“Learn Python”

Many programming languages do implicit conversions when you try to concatenation between string and non string data. In Python however you will see a TypeError.

Example 4:


“Learn Python” + 101


Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    "Learn Python" + 101
TypeError: cannot concatenate 'str' and 'int' objects

Concatenation using .join()

.join() is another useful way to do concatenation in Python. This works well with List which is made up of strings and you want to combine all the strings in this list to give you one big concatenated string result. .join() also takes a “joiner” which should be used in between the strings while joining.

Example 1:


str = ["How" , "Are" , "You"]
‘-’.join(str)

Output

‘How-Are-You’


So now you know how to concatenate strings in Python. There are many other string functions and methods available to do string data manipulations. We will keep on adding such useful information in the future. Bookmark/follow this blog to get the latest updates.

Further Read:

If You Enjoyed This, Take 5 Seconds To Share It