DEV Community

qing
qing

Posted on • Edited 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!*

---
喜欢这篇文章?关注获取更多Python自动化内容!

<!-- paywall-upgrade -->



---

### 🔒 Want More?

This article covers the basics. In **[Content Creator Ultimate Bundle (Save 33%)](https://gumroad.com)** ($29.99), you get:
- Complete source code
- Advanced techniques
- Real-world examples
- Step-by-step tutorials
- Bonus templates

*[Get instant access →](https://gumroad.com)*
Enter fullscreen mode Exit fullscreen mode

Top comments (0)