How to Convert list of tuples to string in Python

Published on Aug. 22, 2023, 12:16 p.m.

To convert a Python list of tuples to a string, you can use the join() function along with a list comprehension that converts the tuples to strings. Here’s an example:

my_list = [('a', 1), ('b', 2), ('c', 3)]
my_string = ', '.join(['{}:{}'.format(item[0], item[1]) for item in my_list])

print(my_string)   # Output: 'a:1, b:2, c:3'

In this example, we define a list my_list containing three tuples, each representing a key-value pair. We use a list comprehension to loop through each tuple in the list and convert it to a string of the form 'key:value' using string formatting. We then use the join() function to join the resulting strings into a single string separated by commas and spaces.

Note that the string formatting used in the list comprehension can be adjusted as per your needs, such as using different separators or adding additional text around the key-value pairs.

In general, converting a list of tuples to a string can be useful when you need to communicate or store data in a compact and easy-to-read format.

Tags:

related content