DEV Community

qing
qing

Posted on

3 Ways to 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 lead to unnecessary indentation in your code. For example, consider the following:

my_string = """
    This is a multiline string
    with multiple lines of text
    and unnecessary indentation"""
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. To avoid this, you can use the textwrap.dedent() function from the textwrap module:


python
import textwrap

my_string = textwrap.dedent("""
    This is

---

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

---

*💡 Related: **Content Creator Ultimate Bundle (Save 33%)** — $29.99*

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

Top comments (0)