我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?
当前回答
Java字符串文字中的大多数转义字符在Python中也有效,例如“\r”和“\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!
正如在其他回答中提到的:“新的行字符是\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
'\n'也是一样,不过你可能不需要'\r'。在Java版本中使用它的原因是什么?如果你确实需要/想要它,你也可以在Python中以同样的方式使用它。
\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.....