Flatten Tuples List to String in Python

PythonServer Side ProgrammingProgramming

When it is required to flatten a list of tuples into a string format, the 'str' method and the 'strip' method can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuples basically contains tuples enclosed in a list. The 'strip' method will remove the specific character/value. The 'str' method will convert the given data type into a string data type.

Below is a demonstration of the same −

Example

Live Demo

my_list = [(11, 14), (54, 56), (98, 0), (13, 76)]

print("The list is : ")
print(my_list)

my_result = str(my_list).strip('[]')

print("The list of tuple flattened to string is: ")
print(my_result)

Output

The list is :
[(11, 14), (54, 56), (98, 0), (13, 76)]
The list of tuple flattened to string is:
(11, 14), (54, 56), (98, 0), (13, 76)

Explanation

  • A list of tuple is defined, and is displayed on the consol.
  • The strip method is used to remove the '[' and ']' brackets.
  • The above method is used after converting the given list of tuple to a string, which is done using the 'str' method.
  • This is assigned to a value.
  • It is displayed on the console.
raja
Published on 12-Mar-2021 05:41:01
Advertisements