This guide explains Multiline Strings and Text Blocks through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
Triple-quoted strings can span lines in source code. They preserve the newlines and indentation you type; textwrap.dedent() can remove incidental shared indentation when formatting multiline templates.
When You Would Use This
Create a two-line notice using literal line breaks.
Step-by-Step Example
notice_text = """Maintenance begins at 09:00.
Please save your work."""
print(notice_text)
print(len(notice_text.splitlines()))
How the Example Works
The result contains two lines. .splitlines() returns two strings, so its length is 2.
Example Output
Maintenance begins at 09:00.
Please save your work.
2
Try It Yourself
Create a three-line checklist and count its lines.
Common Beginner Mistakes
- Adding unintended leading spaces inside a triple-quoted string.
- Expecting triple quotes to interpolate variables automatically.
- Using multiline source formatting without checking the resulting text’s whitespace.
Key Takeaways
- Triple-quoted strings can span lines in source code.
- The result contains two lines.
- Avoid this mistake: Adding unintended leading spaces inside a triple-quoted string.