DEV Community

qing
qing

Posted on

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

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 awkwardly indented code. For example:

my_string = """
    This is a multiline string
    with multiple lines of text
    that is indented for readability
"""
Enter fullscreen mode Exit fullscreen mode

As you can see, the indentation inside the triple quotes is preserved, which can lead to unnecessary whitespace in your string.

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


python
import textwrap

my_string = textwrap.dedent("""
    This is a

---

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

---

*🔧 Related: **Content Creator Ultimate Bundle (Save 33%)** — $29.99 for developers!*

---

If you found this useful, you might like **[Python Interview Prep Guide](https://qssec.gumroad.com)** — a practical resource that takes things a step further. At $24.99 it's a solid investment for your toolkit.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)