Skip to content

Python String Concatenation | Combine Strings

  • by

The string is an object in python, in some cases, you need a combined string. The one way to do it is Python String Concatenation with a ‘ + ” operator.  In a case where you want a merge a 2 string and store value in another variable then use new_String=  first_string + second_string. Python provides several ways to concatenate strings.

Python String Concatenation | Combine Strings example

Ways to Python String Concatenation

  • Plus – using ‘+’ operator
  • Assign – using ‘+=’ operator
  • Using % operator
  • Multiple copies -Using * operator
  • join() Function – For iterators

Syntax 

Simple syntax for string concatenation used ‘+’ operator.

first_string = 'string one'
second_string = 'string two'
merged_string = first_string + second_string

Examples

Here are 5 ways with an example of Python String Concatenation :

Using ‘+’ operator

str1 = 'EyeHunt'
str2 = ' Tutorial'
print(str1 + str2)

Output: EyeHunt Tutorial

Using ‘+=’ operator

str1 = 'EyeHunt'
str1 += ' Tutorial'
print(str1)

Output: EyeHunt Tutorial

Using % operator

str1 = 'Python'
str2 = ' Tutorial'
print('%s%s' % (str1, str2))

Output: Python Tutorial

Using * operator

*  Creates new strings, concatenating multiple copies of the same string.

str1 = 'Abc'

print(str1*3)

Output : AbcAbcAbc

join() Function 

Python Join is a String function (method) and it returns a string, where the elements of the sequence have been joined by a string separator.

Read this tutorial for complete detail and examples  – Python Join Function | Join Strings

str = ",";
list1 = ['EyeHunt', 'Tutorial','Python']
print(str.join(list1))

Output: EyeHunt, Tutorial, python


QA: Interview Questions

# Does int (number) can be Concatenation with string in Python?

str1 = 'EyeHunt'
num = 123
print(str1 + num)

Answers: No, Python can’t concatenate a strings and integer (numbers). They both are separate types of objects in python. So, if you want to merge it, you have to convert the integer to a string.

It will throw an error – TypeError: can only concatenate str (not "int") to str

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of Python String Concatenation are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading