Skip to content
Related Articles

Related Articles

Python | Convert tuple records to single string

View Discussion
Improve Article
Save Article
  • Last Updated : 19 Jun, 2020
View Discussion
Improve Article
Save Article

Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change it’s to comma-separated strings. These can be data regarding names. This kind of problem has its application in the 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 separated by spaces to join them as a single string of records.




# 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 a single string
# Using list comprehension + join()
res = ', '.join([' '.join(sub) for sub in test_list])
      
# printing result
print("The string after tuple conversion: " + res)

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.




# 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 a single string
# Using map() + join()
res = ', '.join(map(" ".join, test_list))
      
# printing result
print("The string after tuple conversion: " + res)

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
Recommended Articles
Page :

Start Your Coding Journey Now!