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


当前回答

'\n'也是一样,不过你可能不需要'\r'。在Java版本中使用它的原因是什么?如果你确实需要/想要它,你也可以在Python中以同样的方式使用它。

其他回答

新的行字符是\n。它用于字符串内部。

例子:

    print('First line \n Second line') 

其中\n是换行符。

这将产生如下结果:

First line
 Second line

如果使用Python 2,则不对打印函数使用圆括号。

\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通常会做这项工作。如果你真的想要正确,你可以在os包中查找换行符。(这实际上叫做linesep。)

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

简单的解决方案

如果只调用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()

Use:

"{}\n{}\n{}".format(
    "line1",
    "line2",
    "line3"
)

我个人更喜欢这种形式。