簡體   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