Python | Convert tuple records to single string

Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change its to comma seperated strings. These can be data regarding names. This kind of problem has it’s application in web development domain. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using join() + list comprehension
In this method, we just iterate through the list tuple elements and perform the join among them seperated by spaces to join them as a single string of records.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert tuple records to single string
# Using list comprehension + join()
  
# Initializing list
test_list = [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert tuple records to single string
# Using list comprehension + join()
res = ', '.join([' '.join(sub) for sub in test_list])
      
# printing result
print("The string after tuple conversion: " + res)

chevron_right


Output :



The original list is : [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
The string after tuple conversion: Manjeet Singh, Nikhil Meherwal, Akshat Garg

 

Method #2 : Using map() + join()
This method performs this task similar to the above function. The difference is just that it uses map() for extending join logic rather than list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert tuple records to single string
# Using map() + join()
  
# Initializing list
test_list = [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert tuple records to single string
# Using map() + join()
res = ', '.join(map(" ".join, test_list))
      
# printing result
print("The string after tuple conversion: " + res)

chevron_right


Output :

The original list is : [('Manjeet', 'Singh'), ('Nikhil', 'Meherwal'), ('Akshat', 'Garg')]
The string after tuple conversion: Manjeet Singh, Nikhil Meherwal, Akshat Garg



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.