代码如下。我真的很困惑dedent()的功能是什么,当我运行这些代码时,结果几乎是一样的。
print(dedent("""
Like a world class boxer you dodge, weave, slip and
slide right as the Gothon's blaster cranks a laser
past your head. In the middle of your artful dodge
your foot slips and you bang your head on the metal
wall and pass out. You wake up shortly after only to
die as the Gothon stomps on your head and eats you.
"""))
print("""
Like a world class boxer you dodge, weave, slip and
slide right as the Gothon's blaster cranks a laser
past your head. In the middle of your artful dodge
your foot slips and you bang your head on the metal
wall and pass out. You wake up shortly after only to
die as the Gothon stomps on your head and eats you.
""")
答案 0 :(得分:3)
基于https://docs.python.org/3.6/library/textwrap.html#textwrap.dedent。
考虑这个有用的例子:
import textwrap
# We have some sample data
data = [[13,"John","New York"],
[25,"Jane","Madrid"]]
# We create a print function
def printfunc(lst):
# This is the string we want to add data to
how_string_could_look_like = """\
age: {}
name: {}
city: {}
"""
# But we can write it this way instead and use dedent:
# Much easier to read right? (Looks neat inside the function)
string = """\
age: {}
name: {}
city: {}
"""
for item in lst:
p = string.format(*item)
print(p) # print without dedent
print(textwrap.dedent(p)) # print with dedent
printfunc(data)
打印:
在第一组和第三组(没有任何人)看到第二和第四组(与dedent)相比。这就是dedent可以做的事情。
age: 13
name: John
city: New York
age: 13
name: John
city: New York
age: 25
name: Jane
city: Madrid
age: 25
name: Jane
city: Madrid
回顾你的例子:
想一想:我想用textwrap.dedent(在每行之前删除空格)是什么意思
没有评论的完整示例
data = [[13,"John","New York"],[25,"Jane","Madrid"]]
def printfunc(lst):
for item in lst:
string = """\
age: {}
name: {}
city: {}
""".format(*item)
print(textwrap.dedent(string))
printfunc(data)