Home > Net >  python string to list (special list)
python string to list (special list)

Time:11-21

I'm trying to get this string into list, how can i do that pleas ?

My string :

x = "[(['xyz1'], 'COM95'), (['xyz2'], 'COM96'), (['xyz3'], 'COM97'), (['xyz4'], 'COM98'), (['xyz5'], 'COM99'), (['xyz6'], 'COM100')]"

I want to convert it to a list, so that:

print(list[0])

Output : (['xyz1'], 'COM95')

CodePudding user response:

If you have this string instead of a list, that presumes it is coming from somewhere outside your control (otherwise you'd just make a proper list). If the string is coming from a source outside your program eval() is dangerous. It will gladly run any code passed to it. In this case you can use ast.liter_eval() which is safer (but make sure you understand the warning on the docs):

import ast

x = "[(['xyz1'], 'COM95'), (['xyz2'], 'COM96'), (['xyz3'], 'COM97'), (['xyz4'], 'COM98'), (['xyz5'], 'COM99'), (['xyz6'], 'COM100')]"

l = ast.literal_eval(x)

Which gives an l of:

[(['xyz1'], 'COM95'),
 (['xyz2'], 'COM96'),
 (['xyz3'], 'COM97'),
 (['xyz4'], 'COM98'),
 (['xyz5'], 'COM99'),
 (['xyz6'], 'COM100')]

CodePudding user response:

If the structure is uniformly a list of tuples with a one-element list of strings and an individual string, you can manually parse it using the single quote as a separator. This will give you one string value every other component of the split (which you can access using a striding subscript). You can then build the actual tuple from pairing of two values:

tuples = [([a],s) for a,s in zip(*[iter(x.split("'")[1::2])]*2)]
print(tuples[0])
(['xyz1'], 'COM95')

Note that this does not cover the case where an individual string contains a single quote that needed escaping

CodePudding user response:

You mean convert list like string into list? Maybe you can use eval(). For example

a="[1,2,3,4]"
a=eval(a)

Then a become a list

CodePudding user response:

to convert as list use x = eval(x)

print(list[0]) will give you an error because list is a python builtin function

you should do print(x[0]) to get what you want

  • Related