2024-04-19 10:33:49 发布
网友
与Java(字符串)相比,您可以做一些类似"First Line\r\nSecond Line"的事情。
"First Line\r\nSecond Line"
那么,在Python中,为了将多行代码写到一个常规文件中,您将如何做到这一点呢?
新行字符是\n。它用在一根绳子里面。
\n
示例:
print 'First line \n Second line'
其中\n是换行符。
这将产生以下结果:
First line Second line
您可以单独写入新行,也可以在单个字符串中写入,这样更容易。
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
正如其他人在前面的答案中指出的,将\n放在字符串中的相关点上:
line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work" file.write(line)
这取决于你想要多正确。\n通常会完成这项工作。如果您真的想把它弄好,可以在^{} package中查找换行符。(它实际上叫做linesep。)
linesep
注意:当使用Python API写入文件时,不要使用os.linesep。只需使用\n;Python会自动将其转换为适合您的平台的换行符。
os.linesep
新行字符是
\n
。它用在一根绳子里面。示例:
其中
\n
是换行符。这将产生以下结果:
您可以单独写入新行,也可以在单个字符串中写入,这样更容易。
例1
输入
您可以分别写“\n”:
输出
例2
输入
正如其他人在前面的答案中指出的,将\n放在字符串中的相关点上:
输出
这取决于你想要多正确。} package 中查找换行符。(它实际上叫做
\n
通常会完成这项工作。如果您真的想把它弄好,可以在^{linesep
。)注意:当使用Python API写入文件时,不要使用
os.linesep
。只需使用\n
;Python会自动将其转换为适合您的平台的换行符。相关问题 更多 >
编程相关推荐