繁体   English   中英

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

[英]Printing List as string in python

我是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]

请给点建议

尝试更换

','.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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM