2017-04-06 139 views
0

字符串我是新手到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] 

請給些建議

回答

0

嘗試通過

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

輸出更換

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

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

另外,不要在你的腳本的末尾不忘f.close()

+0

您也可以使用普通expresson擺脫括號'應用re.sub的(R '[\ [\]', '', '[abc]' 可以)'。根據您輸入的實際情況,可能還有其他選項可以做到這一點。 – Dawid

+0

@Dawid正確的,但我想我會的正則表達式是一個矯枉過正這裏,我會用'.replace堅持()' – TrakJohnson