我如何在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
其他回答
新的行字符是\n。它用于字符串内部。
例子:
print('First line \n Second line')
其中\n是换行符。
这将产生如下结果:
First line
Second line
如果使用Python 2,则不对打印函数使用圆括号。
与平台无关的断行符:Linux、Windows和iOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
这里有一个更易读的解决方案,即使你不在顶级缩进(例如,在函数定义中),它也能正确工作。
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.
"""))
\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.....
Use:
"{}\n{}\n{}".format(
"line1",
"line2",
"line3"
)
我个人更喜欢这种形式。
推荐文章
- 有办法在Python中使用PhantomJS吗?
- 如何在Python中将if/else压缩成一行?
- 如何在Python 3中使用pip。Python 2.x
- 如何让IntelliJ识别常见的Python模块?
- Django:“projects”vs“apps”
- 如何列出导入的模块?
- 转换Python程序到C/ c++代码?
- 如何从gmtime()的时间+日期输出中获得自epoch以来的秒数?
- 在python模块文档字符串中放入什么?
- 我如何在Django中过滤一个DateTimeField的日期?
- 在Python中用索引迭代列表
- -e,——editable选项在pip install中什么时候有用?
- 使用pip命令从requirements.txt升级python包
- Django更改默认的runserver端口
- 输入对象的datetime。Datetime没有Datetime属性