Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the function of dedent() in Python? [duplicate]

Tags:

python

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.
""")
like image 776
Forrest Zhang Avatar asked Dec 11 '25 20:12

Forrest Zhang


1 Answers

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)
like image 199
Anton vBR Avatar answered Dec 13 '25 10:12

Anton vBR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!