Q:

Python program to perform concatenation of two string tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Concatenation of two string tuples

In this article, we are given two tuples with string elements. We will be creating a python program to perform concatenation of two string tuples.

Input:
tup1 = ('python', 'learn', 'web')
tup2 = ('programming', 'coding', 'development')

Output:
('python programming', 'learn coding', 'web development')

One method to solve the problem is by iterating over the tuples and concatenating the string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by using the + operator to concatenate the strings. And use zip along with the generator expression to create a new tuple with string concatenated.

# Python program to perform concatenation 
# of two string tuples

# Initialing and printing tuples
strTup1 = ("python", "learn", "web")
strTup2 = (" programming", " coding", " development")
print("The elements of tuple 1 : " + str(strTup1))
print("The elements of tuple 2 : " + str(strTup2))

# Performing concatenation of string tuples 
concTup = tuple(str1 + str2 for str1, str2 in zip(strTup1, strTup2))

print("The tuple with concatenated string : " + str(concTup))

Output:

The elements of tuple 1 : ('python', 'learn', 'web')
The elements of tuple 2 : (' programming', ' coding', ' development')
The tuple with concatenated string : ('python programming', 'learn coding', 'web development')

Method 2:

Another method to solve the problem is by using concat method to concatenate string values from tuples. Then map these values then convert them to the tuple.

The concat method is imported from the operator library.

# Python program to perform concatenation 
# of two string tuples

import operator 

# Initialing and printing tuples
strTup1 = ("python", "learn", "web")
strTup2 = (" programming", " coding", " development")
print("The elements of tuple 1 : " + str(strTup1))
print("The elements of tuple 2 : " + str(strTup2))

# Performing concatenation of string tuples 
concTup = tuple(map(operator.concat, strTup1, strTup2))

print("The tuple with concatenated string : " + str(concTup))

Output:

The elements of tuple 1 : ('python', 'learn', 'web')
The elements of tuple 2 : (' programming', ' coding', ' development')
The tuple with concatenated string : ('python programming', 'learn coding', 'web development')

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to extract maximum value in record ... >>
<< Python program to perform pairwise addition in tup...