If you have the string "'a','b'" -> as a list("'a','b'") it gets converted to ["'", 'a', "'", ',', "'", 'b', "'"] however I want it to be like: ['a', 'b']
for example:
a = 'a','b' -> list(a) -> ['a', 'b']
If you have the string "'a','b'" -> as a list("'a','b'") it gets converted to ["'", 'a', "'", ',', "'", 'b', "'"] however I want it to be like: ['a', 'b']
for example:
a = 'a','b' -> list(a) -> ['a', 'b']
You could replace and then split on the ,:
>>> "'a','b'".replace("'", "").split(",")
['a', 'b']
Or use a regular expression:
>>> import re
>>> re.findall(r"\w", "'a','b'")
['a', 'b']
Or use evaluation:
>>> import ast
>>> list(ast.literal_eval("'a','b'"))
['a', 'b']
It really depends on your use-case. You could also utilize the CSV module, as @abarnert suggested:
>>> import csv
>>> import io
>>> next(csv.reader(io.StringIO(u"'a','b'"), quotechar="'"))
['a', 'b']
(Note that what works when best also depends on the size of your strings and lists - I cannot link to comments, but please read @abarnert's comments below to get an impression.)
Some benchmarks:
>>> from timeit import timeit
>>> def crude(): "'a','b'".replace("'", "").split(",")
>>> def regex(): re.findall(r"\w", "'a','b'")
>>> def _eval(): list(ast.literal_eval("'a','b'"))
>>> def csvio(): next(csv.reader(io.StringIO(u"'a','b'"), quotechar="'"))
>>> timeit(crude)
1.2010400295257568
>>> timeit(regex)
2.745753049850464
>>> timeit(_eval)
17.016868114471436
>>> timeit(csvio)
3.7680318355560303
next(csv.reader(io.StringIO("'a','b'"), quotechar="'"))? (For the OP's given test case, this is even sillier than regex… but if his real use case can have commas inside the quoted strings, it may not be so bad.)eval. (Then again, maybe you should, since it prevents people from writing Himanshu's answer, making Lattyware happy…)eval.number=10000, crude: 2.52 / 0.11, regex: 15.31 / 11.72, _eval: (killed after >4 min both times), csvio: 2.02 / 0.79. And that's not even taking into account that the real use case could be more complex, in which case either csvio or regex may be much easier to adapt…Or perhaps just this :-
print eval("'a', 'b'")
This prints :-
('a', 'b')