2016-11-29 204 views
0

我正在嘗試將一些字符串寫入文件,但沒有引號。python將字符串寫入不帶引號的文件

我正在讀取列表並試圖將item[0]寫入輸出文件。

我試圖映射和做item[1:-1]但他們都沒有工作。

這是我的代碼:

for item in sorted(wrong_blocks): 
     output.write(str(item[0])) 

此保持寫入文件:

"word" 

,但我只是想:

word 

不帶引號

我檢查這個 Python - how to write strings to file without quotes and spaces?

+0

您的代碼有語法錯誤。它只是缺少括號,還是有更多的東西被截斷? – TigerhawkT3

+0

現在它是正確的 –

+0

你試過'output.write(str(item [0])[1:-1])嗎? – TigerhawkT3

回答

0

您可以刪除從字符串的兩側的給定的字符集的所有實例str.strip

>>> s = '''"hello!"'''.strip('!"') 
>>> print(s) 
hello 

更改output.write調用output.write(str(item[0]).strip('"')),它會刪除任何不必要的報價。

+2

他的代碼看起來不錯,但知道內容'wrong_blocks'會揭示sam_com問題背後的真實原因。但是'.strip(''')'是沒有害處的,如果你真的不需要雙引號這種情況。 –