如何用python打印多行文本

Eno*_*345 20 python python-3.x

如果我想在Python中打印多行文本而不键入print('')每一行,有没有办法做到这一点?我正在将它用于ASCII艺术.

(python 3.5.1)

JRa*_*zor 40

您可以使用三重引号(单个或双重):

a = """
text
text
text
"""

print(a)
Run Code Online (Sandbox Code Playgroud)


Qub*_*uba 10

据我所知,有3种不同的方式.

用于\n打印

print("first line\nSecond line")
Run Code Online (Sandbox Code Playgroud)

用于sep="\n"印刷

print("first line", "second line", sep="\n")
Run Code Online (Sandbox Code Playgroud)

使用三引号和多行字符串

print("""
Line1
Line2
""")
Run Code Online (Sandbox Code Playgroud)

  • 这(尤其是前两种方法)对于包非常有用,这样缩进就不会混乱。 (3认同)

小智 9

我想回答以下与此略有不同的问题:

在多行上打印消息的最佳方式

他也想显示重复字符的线条。他想要这个输出:

----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000

----------------------------------------
Run Code Online (Sandbox Code Playgroud)

您可以使用乘法在 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)
Run Code Online (Sandbox Code Playgroud)


pou*_*aus 7

三引号答案对于 ASCII 艺术来说非常有用,但对于那些想知道的人来说 - 如果我的多行是元组、列表或其他返回字符串的可迭代对象(可能是列表理解?),那么怎么样:

print("\n".join(<*iterable*>))
Run Code Online (Sandbox Code Playgroud)

例如:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))
Run Code Online (Sandbox Code Playgroud)