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


当前回答

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

示例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

其他回答

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

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

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

输出:

physical
distancing

\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.....

正如在其他回答中提到的:“新的行字符是\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

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

这取决于你想要多正确。\n通常会做这项工作。如果你真的想要正确,你可以在os包中查找换行符。(这实际上叫做linesep。)

注意:当使用Python API写入文件时,不要使用os.linesep。只使用\n;Python会自动将其转换为适合您平台的换行符。