从列表中的字符串中转动项目

时间:2017-04-07 12:06:26

标签: python string file

当我读到这样的.txt文件时:

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

我有以下输入:

['k'], ['m']

我想将其转换为:

[k, m]

所以我试试

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

然而,这给了我:

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

对我在这里做错了什么的想法?

2 个答案:

答案 0 :(得分:0)

sting ['k'], ['m']实际上代表了一个列表元组,您只需使用ast.literal_eval()函数将其转换为python元组对象,然后使用itertools.chain()函数链接列表:< / p>

In [1]: s = "['k'], ['m']"

In [2]: import ast

In [3]: ast.literal_eval(s)
Out[3]: (['k'], ['m'])

In [4]: from itertools import chain

In [6]: list(chain.from_iterable(ast.literal_eval(s)))
Out[6]: ['k', 'm']

答案 1 :(得分:0)

您的row似乎是字符串"['k'], ['m']"。如果要将其转换为"[k, m]",则一些简单的replace语句就足够了。首先,删除',然后使用join代替,字符串中的字符,将剩余的] ,[替换为,。< / p>

>>> row = "['k'], ['m']"
>>> row.replace("'", '')
'[k], [m]'
>>> row.replace("'", "").replace("], [", ", ")
'[k, m]'