簡體   English   中英

在文件中顯式寫入換行符

[英]Write newline character explicitly in a file

我是 Python 新手。 我有以下問題:我有一個帶換行符的字符串,我想將此帶換行符的字符串寫入文件。 我希望新行字符在文件中明確可見。 請問我該怎么做? 這是我當前的代碼:

 text = "where are you going?\nI am going to the Market?"
    with open("output.txt",'w', encoding="utf-8") as output:
        output.write(text)

只需用轉義的換行符替換換行符

text = "where are you going?\nI am going to the Market?"
with open("output.txt",'w', encoding="utf-8") as output:
    output.write(text.replace('\n','\\n'))

如果您希望新行字符在您的文件中保持可見而實際上沒有新行,只需在新行字符前添加一個\\

text = "where are you going?\\nI am going to the market?"

print(text)
>>> where are you going?\nI am going to the market?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM