python - Turn items from a string in a list -


when read in .txt file this:

with open("sample.txt") f:  content = f.readlines()  row in content:   print(row) 

i have following input:

['k'], ['m'] 

i transform into:

[k, m] 

so therefore try

with open("sample.txt") f:  content = f.readlines()  row in content:   items = items.replace('\'', '') item in items   row_analyze = ','.join(items) 

this gives me:

[,,k,,],,,[,,m,,], 

any thoughts on doing wrong here?

the sting ['k'], ['m'], represents tuple of lists, can convert python tuple object using ast.literal_eval() function, chain lists using itertools.chain() function:

in [1]: s = "['k'], ['m']"  in [2]: import ast  in [3]: ast.literal_eval(s) out[3]: (['k'], ['m'])  in [4]: itertools import chain  in [6]: list(chain.from_iterable(ast.literal_eval(s))) out[6]: ['k', 'm'] 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -