15

The code is below. What's the function of dedent()?

When I run this code, the result is virtually the same.

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.
""")
4
  • 12
    Of course, if you run dedent over not indented text... Did you read its documentation? Nov 4, 2017 at 14:59
  • 1
  • 2
    What's your dedent, and how are the results only "virtually" the same? Nov 4, 2017 at 15:02
  • 2
    It depends on which dedent is being used. The question says nothing about the standard library textwrap module. It should never have been accepted as is; even supposing we know which dedent we're talking about, the question is directly answered by documentation and it's not clear why there was any confusion in the first place. Jun 10, 2022 at 11:58

1 Answer 1

35

This is based on textwrap.dedent(text).

Consider this example where this can be useful:

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)

Prints:

Look here at the 1st and 3rd group (no dedent) compared to 2nd and 4th (with dedent). This exemplifies what dedent can do.

    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

Looking back at your example:

Think about this: What is it I want to textwrap.dedent (remove whitespace before each line)

Full example without comments

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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.