在python中将列表打印为字符串

时间:2017-04-06 10:22:41

标签: python string list

我是python的新手 如果找到打印行,想要搜索字符串文件 并希望将输出打印为

"mapp1=2"
"map2=6"
"MAP3"

示例代码:

import os
fname = "xx.txt"

new_list=[]
f=open(fname,'r')
for line in f :
    key = line.strip().split('\n')
    matching = [s for s in key if ("mapping" or "MAP") in s]
    if matching:
       if not line.startswith("#"):
           new_list.append((key))

print new_list

values = ','.join(str(i) for i in new_list)
print values

failed_res = ','.join(str(j) for j in values)
print failed_res

此代码的输出为:

[mapp1=2],[map2=6],[MAP]

请提出一些建议

1 个答案:

答案 0 :(得分:0)

尝试替换

','.join(str(i) for i in new_list)

通过

'\n'.join(str(i).replace('[', '"').replace(']', '"') for i in new_list)

输出:

"mapp1=2"
"map2=6"
"MAP"

另外,请不要忘记脚本末尾的f.close()