Q:

Python program to concatenate tuple elements by delimiter

belongs to collection: Python Tuple Programs

0

Example:

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

Concatenating Tuple elements by Delimiter

We have a tuple consisting of elements and a delimiter string. And we need to concatenate the values to a string.

Input:
tuple = ("Python", "program", 5, "scala"), delimiter = “-”

Output:
Python-program-5-scala

For performing this task, we have more than one method to solve the problem.

 

All Answers

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

Method 1:

To concatenate the tuples, we will use the str() to convert all characters to string and then concatenate them with a delimiter using join() method.

The map is used to perform the mapping of the string.

# Python program to concatenate tuples 
# using delimiter 

# Creating and printing the tuple and delimiter
myTuple = ("Python", "program", 5, "scala")
print("Tuple values are " + str(myTuple))
delimiter = "-"

# Concatenating the tuple using delimiter 
concatenated = delimiter.join(map(str, myTuple))

# printing Concatenated string 
print("Concatenated Tuple with delimiter : " + str(concatenated))

Output:

Tuple values are ('Python', 'program', 5, 'scala')
Concatenated Tuple with delimiter : Python-program-5-scala

Method 2:

Another method to solve the problem is by using list comprehension where we will loop through the tuple and using the + operator add a delimiter to the string.

# Python program to concatenate tuples 
# using delimiter 

# Creating and printing the tuple and delimiter
myTuple = ("Python", "program", 5, "scala")
print("Tuple values are " + str(myTuple))
delimiter = "-"

# Concatenating the tuple using delimiter 
concatenated = ''.join([str(ele) + delimiter for ele in myTuple])

# Logic for removing the ending delimiter...
concatenated = concatenated[ : len(concatenated) - len(delimiter)]

# Printing Concatenated string 
print("Concatenated Tuple with delimiter : " + str(concatenated))

Output:

Tuple values are ('Python', 'program', 5, 'scala')
Concatenated Tuple with delimiter : Python-program-5-scala

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 all symmetric tuples... >>
<< Python program to perform cross pairing in tuple l...