我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?


当前回答

这里有一个更易读的解决方案,即使你不在顶级缩进(例如,在函数定义中),它也能正确工作。

import textwrap
file.write(textwrap.dedent("""
    Life's but a walking shadow, a poor player
    That struts and frets his hour upon the stage
    And then is heard no more: it is a tale
    Told by an idiot, full of sound and fury,
    Signifying nothing.
"""))

其他回答

在Python中,你可以只使用换行符,即\n

值得注意的是,当你使用交互式Python shell或Jupyter Notebook检查字符串时,\n和其他反划字符串(如\t)会逐字呈现:

>>> gotcha = 'Here is some random message...'
>>> gotcha += '\nAdditional content:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet even more great stuff!'

换行符、制表符和其他特殊的非打印字符只有在打印或写入文件时才会呈现为空白:

>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
    Yet even more great stuff!

简单的解决方案

如果只调用print而不带任何参数,它将输出一个空行。

print

你可以像这样将输出管道到一个文件中(考虑到你的例子):

f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f
f.close()

它不仅与操作系统无关(甚至不需要使用操作系统包),而且比将\n放在字符串中更具可读性。

解释

print()函数有一个可选的关键字参数,用于字符串的结尾,称为end,默认为操作系统的换行符,例如。\ n。所以,当你调用print('hello')时,Python实际上打印的是'hello' + '\n'。这意味着当你只调用print而不带任何参数时,它实际上打印的是" + '\n',结果是换行符。

替代

使用多行字符串。

s = """First line
    Second line
    Third line"""
f = open('out.txt', 'w')
print s >> f
f.close()

Java字符串文字中的大多数转义字符在Python中也有效,例如“\r”和“\n”。

\n -简单换行符插入工作:

# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!\n testing first line.. \n testing second line.. \n and third line....."

输出:

In [37]: print(test_line)

Hi!!!
 testing first line..
 testing second line..
 and third line.....