Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

String Concatenation in Python with Examples

Tags: string

String concatenation means joining or combining two or more strings. Joining of two or more strings to make them one is called String concatenation in Python.

In general, Python provides (+) operator to concatenate multiple strings. We can concatenate two or more strings, or a string with a number or symbol to display information as per requirements.

For example, when you fill an online registration form, you fill your first name, middle name, and last name in three separate columns.

But when you finish the form, then you see your complete name as a single string. This is a realtime use of string concatenation in Python. Let’s write the code for it.

Example:

# Python program to demonstrate the string concatenation.
# Take first name as input from the user.
first_name = input('Enter your first name: ')

# Take middle name as input from the user.
middle_name = input('Enter your middle name: ')

# Take last name as input from the user.
last_name = input('Enter your last name: ')

# Concatenate strings using + operator.
string_concatenation = first_name + " " + middle_name + " " +last_name
print("Full name:",string_concatenation)
Output:
      Enter your first name: Tripti
      Enter your middle name: Deepak
      Enter your last name: Priya
      Full name: Tripti Deepak Priya

In the above example code, we have taken first name, middle name, and last name as inputs from the user using input() function and stored into variables named first_name, middle_name, and last_name, respectively.

Then, we have concatenated all strings using (+) operator, stored in a variable named string_concatenation, and printed it on the console. Thus, we can combine several strings into one large string using the + operator.

Ways to Concatenate Strings in Python


String concatenation is heavily used in Python programming. There are five convenient and best ways to concatenate strings. They are as:

  • Using + operator
  • Using join() method
  • By using % operator
  • By using format() function
  • Using f-string (Literal String Interpolation)

Let’s understand all five methods one by one with the help of example programs.

String Concatenation using + Operator


It is straightforward and convenient way to concatenate or appending two or more strings in Python. It can add multiple strings together to make them one. Let’s take an example based on it.

Example 1:

# Python program to join three strings.
str1 = 'Python'
str2 = ' Programming' # string with a space.
str3 = ' Language' # string with a space.

concatenated_string = str1 + str2 + str3
print('Joined string:',concatenated_string)
Output:
      Joined string: Python Programming Language

In the above program, we have used (+) operator to join three strings and forms a new string.

Example 2:

# Python program to join a number with a string.
num = 25
str = 'twenty-five'
# Joining a number with string.
concatenated_string = num + str
print('Joined string:',concatenated_string)
Output:
       TypeError: unsupported operand type(s) for +: 'int' and 'str'

In the above example, we have used the (+) operator to concatenate two values of different data types. We are trying to join string data type with integer data type. Therefore, Python generates TypeError error.

To concatenate integer number with a string, you first need to convert integer data type into string data type using str() function and then concatenate both string values. Let’s take an example on it.

Example 3:

# Python program to join two strings.
num = 20
# This statement converts integer type into string type.
str1 = str(num) # returns a string version of the object.
str2 = 'twenty'

# Joining two strings.
concatenated_string = str1 + str2
print('Joined string:',concatenated_string)
Output:
      Joined string: 20twenty

In the above code, we have used str() function to convert an integer data type into string data type. This function returns a string version of object. If we do not provide any object, it returns an empty string. The general syntax for this function is as:

str(object)

Note:

Python does not allow to concatenate string value with integer value as they are of different data types. You will have to convert integer type into string type before concatenating integer and string values.


You can also concatenate an integer type with string type without using str() function if you write integer type into string type. Look at the below example.

Example 4:

# Python program to join two strings.
str1 = '25' # number in string type.
str2 = 'twenty-five'
# Joining strings.
concatenated_string = str1 + str2
print('Joined string:',concatenated_string)
Output:
      Joined string: 25twenty-five

Repetition of String using Multiplication (*) Operator


We can use the multiplication operator (*) to repeat a string number of times. For example, to repeat a string “world” three times, you simply type the string and specify the number of times as *3. Let’s take an example program based on it.

Example 5:

# Python program to repeat a string number of times.
str = 'Love' * 4 # Multiplying strings.
print('Repeated string:',str)
Output:
       Repeated string: LoveLoveLoveLove

In the above example, we have repeated a string four times.

Example 6:

str1 = 'Python'
str2 = str1 * 2
print(str2)

str3 = (str2) * 2
print(str3)

str4 = 2 * ('Love', 'Python')
print(str4)
Output:
      PythonPython
      PythonPythonPythonPython
      ('Love', 'Python', 'Love', 'Python')

String Concatenation using join() Method


We can join strings by using join() method. This function provides a flexible way to concatenate strings. The general syntax for join() method is as:

string_name.join(sequence)

In the above syntax, sequence can be string or list. If the specified sequence in this function is string, then join() function inserts string_name between each character of string sequence and returns joined string.

If the sequence is a list, join() function inserts string_name between each element of list sequence and returns joined string. Remember that all the elements in the list should be of string type. Let’s take an example program based on it.

Example 7:

# Python program to concatenate strings using join() method.
first_name = 'Ivaan'
middle_name = 'Vidya'
last_name = 'Sagar'

# This statement inserts blank space between each sequence of strings.
full_name = ' '.join((first_name, middle_name, last_name))
print("Full name:",full_name)

dob = ["23","12","2016"]
my_dob = '/'.join(dob)
print('Date of birth:',my_dob)
Output:
      Full name: Ivaan Vidya Sagar
      Date of birth: 23/12/2016

In this example, we have inserted a blank space between each sequence of string using join() function and stored returned concatenated string in the variable full_name.

In dob list variable, all the elements in the list are of string type. We have inserted ‘/’ between each of the list elements and stored the returned joined string into a variable my_dob and then displayed it on the console.

Example 8:

# Python program to concatenate strings using join() method.
str = 'Scientech'
str2 = 'Easy'
institute_name = " ".join((str, str2))
print('Institute name:',institute_name)

address = ['Dhanbad','Jharkhand']
print('Address:',", ".join(address))
Output:
      Institute name: Scientech Easy
      Address: Dhanbad, Jharkhand

Example 9:

# Python program to insert a number between each character of string using join() method.
num = "2"
str = 'abcd'
joined_string = num.join(str)
print(joined_string)
Output:
      a2b2c2d

In this example, variables num and str are of string type. The string value “2” is placed between each character of “abcd” string resulting in “a2b2c2d2”. The string value “2” is inserted between a and b, and again between b and c, and so on. Then, it is assigned to joined_string variable.

Joining Strings using Formatting Operator (%)


We can also use a string formatting operator (%) for joining two or more strings or string and number. Let’s take a simple example based on it.

Example 10:

# Python program to concatenate strings using formatting operator %.
first_name = 'John'
last_name = 'Smith'
full_name = "% s % s" % (first_name, last_name)
print('Full name:',full_name)

day = 20
month = 'Oct'
year = 2002
dob = "% s % s % s" % (day, month, year)
print("Date of birth:",dob)
Output:
      Full name: John Smith
      Date of birth: 20 Oct 2002

In this example, we have used %s within double quotation marks that is used for a string conversion via str() function before formatting.

Concatenating String using format() function


We can also use format() function to concatenate strings. This function uses positional formatting to concatenate string in the sequence. We use curly braces ({ }) to position a sequence of strings in a specific order.

Example 11:

# Python program to concatenate strings using format() function.
first_name = 'John'
last_name = 'Smith'
full_name = "{} {}".format(first_name, last_name)
print('Full name:',full_name)

day = 12
month = 'Nov'
year = 2010
dob = "{} {} {}".format(day, month, year)
print("Date of birth:",dob)
Output:
      Full name: John Smith
      Date of birth: 12 Nov 2010

In this example, we have stored the variable first_name in the first set of curly braces, variable last_name in the second set of curly braces, and so on. Then, we have stored the combined string in the variable full_name, and displayed it on the console. Similarly, for dob.

String Concatenation using f-string


If you are using Python 3.6+, you can also use f-string for concatenating strings. PEP 498 introduced a new way to format strings known as Literal String Interpolation or f-string. To create an f-string, prefix the string with the letter “ f ”. Let’s take a simple example of it.

Example 12:

# Python program to concatenate strings using f-strings.
fName = 'John'
sName = 'Smith'
fName = f'{fName} {sName}'
print('Full name:', fName)

age = 34
print('Age:',f'{age}')
Output:
      Full name: John Smith
      Age: 34

In this tutorial, you have learned about string concatenation in Python with various examples. Hope that you will have understood the basic points of string concatenation and practiced all example programs.
Thanks for reading!!!

The post String Concatenation in Python with Examples appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

String Concatenation in Python with Examples

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×