Textwrap.dedent() does not work

Hey!

For some reason the dedent function doesn’t work for me… Can anyone tell me why?

This is my code:

 from textwrap import dedent
 
 print(">>>> Here will be a dedenting test:")
 print(dedent("""Helllooo
             Helllooooo
                     Test!!"""))

This is the output:

>>>> Here will be a dedenting test:
Helllooo
            Helllooooo
                    Test!!

Maybe it’s something very obvious that I am missing… But I really don’t see it :face_with_raised_eyebrow:

Thanks for your help :slight_smile:

Summary

This text will be hidden

Hi @leonvdb you did nothing wrong, it’s the design of textwrap.dedent: On the first line you have to set the ammount of space you want to dedent in the lines below, otherwise it will capture the position of the first text to set the next lines appropriate to it. The first intent it finds is the indent it will strip away. So if you have some text on the first line it will set it’s position to dedent the next lines:

Example with first line empty:

from textwrap import dedent

print(">>>> Here will be a dedenting test:")
print(dedent("""
    First Line
    Helllooo
    Hellooooo
    Test!!"""))

Creates a empty line over the dedented text:

>>>> Here will be a dedenting test:

First Line
Helllooo
Hellooooo
Test!!

Example with text on first line:

from textwrap import dedent

print(">>>> Here will be a dedenting test:")
print(dedent("""First Line
    Helllooo
    Hellooooo
    Test!!"""))
>>>> Here will be a dedenting test:
First Line
    Helllooo
    Hellooooo
    Test!!

If you set the same amount of spaces on the first line as you have for the further indents in the lines below you can accomplish the same without a empty line over the text:

from textwrap import dedent

print(">>>> Here will be a dedenting test:")
print(dedent("""    First Line
    Helllooo
    Hellooooo
    Test!!"""))
>>>> Here will be a dedenting test:
First Line
Helllooo
Hellooooo
Test!!
3 Likes

very helpful! Thank you :slight_smile:

I’m glad that I could help.