Python中的dedent()函数有什么作用?

13

以下是代码。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.
""")

12
当然,如果你对没有缩进的文本运行 dedent... 你有阅读过它的文档吗? - Matteo Italia
1
请查看此处:https://docs.python.org/3.6/library/textwrap.html#textwrap.dedent - Anton vBR
2
你的“dedent”是什么,它为什么只有“虚拟上”相同的结果? - Stefan Pochmann
1
可能是重复的问题:Python是否有用于取消缩进多行字符串的内置函数? - Michał Zaborowski
2
这要取决于使用哪个dedent。问题并未涉及标准库的textwrap模块。事实上,它从一开始就不应该被接受;即使我们知道我们正在讨论哪个dedent,问题在文档中已经有了直接的答案,而且不清楚为什么会有任何困惑 - Karl Knechtel
1个回答

33

这基于textwrap.dedent(text)

考虑以下例子,它可以很有用:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接