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


当前回答

值得注意的是,当你使用交互式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!

其他回答

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

正如在其他回答中提到的:“新的行字符是\n。它在字符串中使用”。

我发现最简单易读的方法是使用“format”函数,使用nl作为新行名称,并将你想打印的字符串转换为你要打印的确切格式:

Python 2:

print("line1{nl}"
      "line2{nl}"
      "line3".format(nl="\n"))

Python 3:

nl = "\n"
print(f"line1{nl}"
      f"line2{nl}"
      f"line3")

这将输出:

line1
line2
line3

通过这种方式,它可以执行任务,并且还提供了代码的高可读性:)

您可以单独写入新行,也可以在单个字符串中写入,这样更容易。

示例1

输入

line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"

你可以把“\n”分开写:

file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")

输出

hello how are you
I am testing the new line escape sequence
this seems to work

示例2

输入

正如其他人在之前的回答中指出的那样,将\n放在字符串中的相关点:

line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"

file.write(line)

输出

hello how are you
I am testing the new line escape sequence
this seems to work

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

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.
"""))

与平台无关的断行符:Linux、Windows和iOS

import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)

输出:

physical
distancing