Python | Convert String to tuple list

Sometimes, while working with Python strings, we can have a problem in which we receive a tuple list in the comma seperated string format and has to converted to tuple list. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop + split() + replace()
This is brute force method to perform this task. In this, we perform the task of extracting and remaking the tuples to list in a loop using split() and replace() functionalities.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert String to tuple list
# using loop + replace() + split()
  
# initializing string 
test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)"
  
# printing original string 
print("The original string is : " + test_str)
  
# Convert String to tuple list
# using loop + replace() + split()
res = []
temp = []
for token in test_str.split(", "):
    num = int(token.replace("(", "").replace(")", ""))
    temp.append(num)
    if ")" in token:
       res.append(tuple(temp))
       temp = []
  
# printing result
print("List after conversion from string : " + str(res))

chevron_right


Output :



The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6)
List after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)]

 

Method #2: Using eval()
This inbuilt function can also be used to perform this task. This function internally evaluates the string and returns the converted list of tuples as desired.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert String to tuple list
# using eval()
  
# initializing string 
test_str = "(1, 3, 4), (5, 6, 4), (1, 3, 6)"
  
# printing original string 
print("The original string is : " + test_str)
  
# Convert String to tuple list
# using eval()
res = list(eval(test_str))
  
# printing result
print("List after conversion from string : " + str(res))

chevron_right


Output :

The original string is : (1, 3, 4), (5, 6, 4), (1, 3, 6)
List after conversion from string : [(1, 3, 4), (5, 6, 4), (1, 3, 6)]


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.