2016-07-15 51 views
1

我這一小段代碼爲我的某種操作系統的字符串:「 n」個不工作

print("Type your document below.") 
print("Press enter to save.") 
print("Type \\n for a new line.") 
file=input() 
print("Enter a file name...") 
filename=input() 
outFile = open(filename, "w+") 
outFile.write(file) 
outFile.close() 

但是當我運行該代碼(這在DEF),說我輸入的東西像這樣:

foo \n bar 

因爲從用戶接收輸入時進入不工作,所以你必須使用\ n。

文件證明爲:

foo \n bar 

代替:

foo 
bar 
+0

在一個字符串中防止實際製作一個新行,而不是'爲新行輸入(新行)'它是'Type \ n for new line'。 – Xtreme

回答

1

正如馬亭解釋你需要自己處理的替代品。要做到這一點最簡單的方法是從字面上與.replace方法:

>>> print(input('Enter \\n for newline: ').replace('\\n', '\n')) 
Enter \n for newline: This is my \nnewline 
This is my 
newline 

這將正常工作的\n轉義序列,但如果你希望其他人(例如\t),那麼你就需要實現自己。

+0

非常感謝你,寫一個文件怎麼樣?同樣的事情會起作用嗎? – Xtreme

+0

我不確定你在問什麼。爲什麼不嘗試呢? –

+0

它的工作,謝謝 – Xtreme

5

\n是一個轉義序列只能在字符串文字input()不接受字符串文本,它接受用戶輸入的文本並且不對其進行任何處理,因此任何輸入\後接n的人都會產生一個由兩個字符組成的字符串,即反斜槓和字母n,而不是換行符。

你必須做你自己的這種處理逃脫自己:

file = file.replace(r'\n', '\n') 

這裏我使用了原始字符串字面量,這也並不支持轉義序列,定義反斜線\其次一個n

另外,反覆要求用戶提供一個新的文件名,直到他們完成:

lines = [] 
print('Type in your document, followed by a blank line:') 
while True: 
    line = input("> ") 
    if not line: 
     break 
    lines.append(line) 
file = '\n'.join(lines) 

演示:

>>> lines = [] 
>>> print('Type in your document, followed by a blank line:') 
Type in your document, followed by a blank line: 
>>> while True: 
...  line = input("> ") 
...  if not line: 
...   break 
...  lines.append(line) 
... 
> foo 
> bar 
> 
>>> lines 
['foo', 'bar'] 
>>> '\n'.join(lines) 
'foo\nbar' 
+0

我該怎麼做? – Xtreme

1

注意,如果你想支持Python風格的字符串(不僅\n\t\r\u1234,等等),你應該使用codecs.decodeunicode_escape處理程序:

contents = input() 
contents = codecs.decode(contents, "unicode_escape") 

注意這將改變

foo\nbar\\nbash\u1234 

foo 
bar\nbashሴ 

您還需要處理錯誤。您可以通過緩存UnicodeDecodeError或使用錯誤替換策略做到這一點:

contents = input() 
contents = codecs.decode(contents, "unicode_escape", errors="replace") 

可悲的是,這似乎亂用Unicode字符:

codecs.decode(r"α", "unicode_escape") 
#>>> 'α' 

我所知道的是:先逃離簡單的解決辦法raw_unicode_escape

contents = input() 
contents = codecs.encode(r"α", "raw_unicode_escape") 
contents = codecs.decode(inp, "unicode_escape") 

這可能是更爲複雜比你需要的,所以我建議實際上沒有這樣做。