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
Thanks for your help
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
I’m glad that I could help.