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

时间:2013-12-12 01:56:06

标签: python

我正在尝试打印字符串到文件,但我想这样:

string = "asdfasdf \n awefawe"

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

asdfasdf \n awefawe

AND NOT

asdfasdf
 awefawe

我该怎么做?我试过了:

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

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

4 个答案:

答案 0 :(得分:4)

修改string的定义,使其最终包含\n而不是换行符。这可以通过以下任一方式完成:

string = r"asdfasdf \n awefawe"

或:

string = "asdfasdf \\n awefawe"

答案 1 :(得分:4)

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

>>> 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个对象中。

答案 2 :(得分:1)

Python将字符串中的\n解释为换行符。因此,要打印文字反斜杠,只需使用另一个反斜杠转义反斜杠,如下所示:

string = "asdfasdf \\n awefawe"

答案 3 :(得分:0)

你必须逃避反斜杠。

string = "asdfasdf \\n awefawe"