Concatenate Strings | How to concatenate Strings in Python

Published January 03, 2021

In Python Programming some time we face a scenario to concatenate string. We know, two join two strings we will use the '+' operator in many programming examples.

Today we are going to learn how to concatenate strings in a python program.

 

Let's get started. 

We have a simple python program with two string variable like below

 

# Python program with Strings

  
  
# A variable var1 having the value python 
var1 = "Python"
  
# A variable var1 having the value python
var2 = "Strings"
  
# print the result 
print(var1) 
print(var2) 

 

Output

Python
Strings

 

Concatenate String in Python

Now how we will concatenate these two strings. 

Python we have below ways to concatenate String

  • Using + operator
  • Using % operator
  • Using join() method
  • Using format() function

 

Using + operator

Using the '+' operator we can concatenate multiple strings in python. With the '+' operator it is an easy way we can join the string. To use this '+' operator both variables should be a String.

 

# Python program with Strings

  
  
# A variable var1 having the value python 
var1 = "Python "
  
# A variable var1 having the value python
var2 = "Strings"

var3 =var1+var2  
# print the result 
print(var3) 

 

Output:

It will print Python Strings

 

Using % Operator

This is a String Formatter operator. With the '%' operator we can format any string.

# Python program with Strings

  
  
# A variable var1 having the value python 
var1 = "Python"
  
# A variable var1 having the value python
var2 = "Strings"

# % Operator is used here to combine the string 
print("% s % s" % (var1, var2)) 

 

Using join() method

The string contains a method called join() which will join the one string with other string values.

# Python program with Strings

# A variable var1 having the value python 
var1 = "Python "
  
# A variable var1 having the value python
var2 = "Strings"

var3="".join([var1,var2])
print(var3 )

 

Using format()

# Python program with Strings

# A variable var1 having the value python 
var1 = "Python "
  
# A variable var1 having the value python
var2 = "Strings"

# format function is used here to  
# combine the string 
print("{} {}".format(var1, var2))

 

Output:

Python  Strings

 

Know more python course for beginner

Python Remove Last Character From String 

 

Tags: Python Strings, String Concatenation, String join, format

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

932 Views