Method # 1: Using str () + strip ()
A combination of the above functions can be used to solve this problem. In this we just convert the list to a string and strip the opening, closing square brackets of the list to represent the string.
# Python3 code to demonstrate how it works # List of tuples to string # using str () + strip () # initialize the list test_list = [( 1 , 4 ), ( 5 , 6 ), ( 8 , 9 ), ( 3 , 6 )] # print original list print ( "The original list is:" + str (test_list)) # List of tuples per string # using str () + strip () res = str (test_list) .strip ( ’[]’ ) # print result print ( " Resultant string from list of tuple: " + res) |
Output:
The original list is: [(1, 4), (5, 6), (8, 9), (3, 6)] Resultant string from list of tuple: (1, 4), (5, 6), (8 , 9), (3, 6)
Method # 2: Using map () + join ()
This is another way to accomplish this task. In this we apply a string conversion function to each element and then join the tuples using join ()
.
# Python3 code for demonstrations # List of tuples in a string # using map () + join () # initialize the list test_list = [( 1 , 4 ), ( 5 , 6 ), ( 8 , 9 ), ( 3 , 6 )] # print original list print ( "The original list is:" + str (test_list)) # List of tuples per string # using map () + join () res = "," . join ( map ( str , test_list)) # print result print ( "Resultant string from list of tuple:" + res) |
The output:
The original list is: [(1, 4), (5, 6), (8, 9), (3, 6) ] Resultant string from list of tuple: (1, 4), (5, 6), (8, 9), (3, 6)
Python | List of tuples per string Python functions: Questions
Python | List of tuples per string String Variables: Questions