Skip to main content
 首页 » 编程设计

Python,打印到文件没有 "\n"的功能

2025年05月04日12powertoolsteam

我正在尝试将字符串打印到文件中,但我希望这样:

string = "asdfasdf \n awefawe" 

我希望它按原样打印。所以文件包含:

asdfasdf \n awefawe 

与非

asdfasdf 
 awefawe 

我该怎么做?我试过:

f1=open('./testfile.txt', 'w+') 
f1.write(body) 

编辑:我不想更改字符串 我只想按原样打印它。甚至到标准输出。我不在乎在哪里。我想知道字符串包含什么。它不仅仅是关于 \n

请您参考如下方法:

如果您无法修改设置 string 值的代码(如其他答案所建议),您可以使用 Python-specific codecs 之一将“特殊”字符转换为等效的 Python 字符串文字转义序列:

>>> print "abc\ndef".encode("string_escape") 
abc\ndef 

如果字符串可能包含非 ASCII 字符,您可能需要 unicode_escape,具体取决于您的更大要求:

>>> print "Ā".encode("string_escape") 
\xc4\x80 
>>> print u"Ā".encode("unicode_escape") 
\u0100 

从技术上讲,string_escape 只能应用于 byte 字符串,而 unicode_escape 只能应用于 Unicode 字符串,但是 Python 2只要所有字符都在 ASCII 范围内(即 U+0000 到 U+007F),您就可以使用其中任何一个。我不确定 Python 3 的等价物是什么——.encode 方法似乎不存在于 3.2 中的 bytes 对象上......