DEV Community

qing
qing

Posted on

Quick Tip: Use `textwrap.dedent()` for clean multiline strings

Quick Tip: Use textwrap.dedent() for clean multiline strings

When working with multiline strings in Python, it's common to use triple-quoted strings. However, these can often lead to unnecessary indentation in your code. For example:

my_string = """
    This is a multiline string
    with unnecessary indentation
    that can make your code look messy
"""
Enter fullscreen mode Exit fullscreen mode

As you can see, the indentation inside the triple-quoted string is preserved, which can lead to inconsistent formatting in your code.

To avoid this, you can use the dedent() function from the textwrap module:


python
from textwrap import dedent

my_string = dedent("""
    This is a

---

*Follow me on Dev.to for daily Python tips and quick guides!*

---

*🛠️ Useful resource: **Content Creator Ultimate Bundle (Save 33%)** — $29.99. Check it out on Gumroad!*
Enter fullscreen mode Exit fullscreen mode

Top comments (0)