我如何在Python中指明字符串中的换行符,以便我可以将多行写入文本文件?
当前回答
新的行字符是\n。它用于字符串内部。
例子:
print('First line \n Second line')
其中\n是换行符。
这将产生如下结果:
First line
Second line
如果使用Python 2,则不对打印函数使用圆括号。
其他回答
这里有一个更易读的解决方案,即使你不在顶级缩进(例如,在函数定义中),它也能正确工作。
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。它在字符串中使用”。
我发现最简单易读的方法是使用“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 -简单换行符插入工作:
# 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"
)
我个人更喜欢这种形式。
与平台无关的断行符:Linux、Windows和iOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
输出:
physical
distancing
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象