如何使用python打印多行文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34980251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print multiple lines of text with python
提问by Eno 12345
If I wanted to print multiple lines of text in Python without typing print('')
for every line, is there a way to do that? I'm using this for ASCII art.
如果我想在 Python 中打印多行文本而不print('')
为每一行打字,有没有办法做到这一点?我将它用于 ASCII 艺术。
(python 3.5.1)
(蟒蛇 3.5.1)
采纳答案by JRazor
You can use Triple quotes (single ' or double "):
您可以使用三重引号(单 ' 或双 "):
a = """
text
text
text
"""
print(a)
回答by Quba
As far as i know there are 3 different ways.
据我所知,有3种不同的方式。
Use \n
in your print
\n
在您的印刷品中使用
print("first line\nSecond line")
use sep="\n"
in print
sep="\n"
在印刷中使用
print("first line", "second line", sep="\n")
Use triple quotes and multiline string
使用三引号和多行字符串
print("""
Line1
Line2
""")
回答by pourhaus
The triple quotes answer is great for ascii art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:
三重引号答案非常适合 ascii 艺术,但对于那些想知道的人 - 如果我的多行是元组、列表或其他返回字符串的可迭代对象(也许是列表理解?),那么怎么样:
print("\n".join(<*iterable*>))
For example:
例如:
print("\n".join([ "{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k ]))
回答by Miklos Horvath
I wanted to answer to the following question which is a little bit different than this:
我想回答以下与此略有不同的问题:
best way to print messages on multiple line
He wanted to show lines from repeated characters too. He wanted this output:
他也想显示重复字符的线条。他想要这个输出:
----------------------------------------
# Operator Micro-benchmarks
# Run_mode : short
# Num_repeats : 5
# Num_runs : 1000
----------------------------------------
You can create those lines inside f-strings with a multiplication, like this:
您可以使用乘法在 f 字符串中创建这些行,如下所示:
run_mode, num_repeats, num_runs = 'short',5,1000
s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode : {run_mode}
# Num_repeats : {num_repeats}
# Num_runs : {num_runs}
{'-'*40}
"""
print(s)