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

2024-04-23 17:50:37 发布

您现在位置: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]

请给出一些建议


Tags: key代码inmapnewforifline
1条回答
网友
1楼 · 发布于 2024-04-23 17:50:37

尝试替换

','.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()。你知道吗

相关问题 更多 >