Home > Back-end >  Convert string to list of tuples in python
Convert string to list of tuples in python

Time:06-25

I have a string that looks like this:

string = "(a1, a2), (b1, b2), (c1, c2), ..."

and I want to convert it to a list of tuples, like so

result = [('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2'), ...]

My initial idea was to add quotation marks to every a1, a2, b1, etc, and then apply the eval function to the result. But I am kind stuck, since each a1, a2, b1 can be any string. Can someone help me out, please.

CodePudding user response:

assuming your inside strings don't have ',' or '()', and there is a space after comma.. this works

import re
string = "(a1, a2), (b1, b2), (c1, c2)"
print( [tuple(string.split(', ')) for string in re.findall("\(([^\)]*)\)", string)] )

Output:

[('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2')]

CodePudding user response:

That would also work, in case you didn't want to import library

string = "(a1, a2), (b1, b2), (c1, c2)"
string = string.replace('), ', ');')
list = list(string.split(';'))
list_tuple = []
for tem in list:
    tem = tem.replace('(', '')
    tem = tem.replace(')', '')
    tem = tem.replace(' ', '')
    tem1 = tuple(tem.split(','))
    list_tuple.append(tem1)
print(list_tuple)

Output:

[('a1', 'a2'), ('b1', 'b2'), ('c1', 'c2')]
  • Related