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
Post a Comment