Multiline Strings in Python: What Each Approach Actually Stores
A practical review of Python multiline string options: triple quotes, dedent, adjacent literals and escaping. Covers what changes in the value and how it holds up when copied.
Python offers several ways to write text that spans more than one line of source code. They look similar on screen, but they do not store the same characters. Some keep every line break and indentation space exactly as typed. Others join pieces into one line. Some process escape sequences and some leave backslashes alone. This review compares the common approaches by what ends up in the string value, how well each holds up when code is copied or shared, and when the text belongs in a plain file instead of a literal.
Short answer: which approach suits which job
- Use a triple-quoted string when the line breaks are part of the content, such as help text, templates, SQL or sample data.
- Add a backslash right after the opening quotes and wrap the literal in textwrap.dedent when it sits inside indented code.
- Use adjacent string literals inside parentheses when you want one logical line that is only wrapped in the source.
- Use a separate plain-text file when the text is long, is edited by people who do not work in Python, or must match an external file exactly.
The main benefit of triple-quoted strings is that the source looks like the result. The main tradeoff is that the source layout and the string content are coupled. Indentation, a leading newline and trailing spaces inside the quotes all become part of the value unless you remove them on purpose.
What each approach changes in the stored value
| Approach | Line breaks in the value | Source indentation in the value | Escape sequences processed |
| Triple-quoted string ("""...""" or '''...''') | Yes, one per source line break | Yes, unless removed afterwards | Yes |
| Raw triple-quoted string (r"""...""") | Yes | Yes | No; backslashes are kept as typed |
| Adjacent literals inside parentheses | Only where \n is written | No; whitespace between literals is not part of the value | Yes, within each piece |
| Backslash at the end of a line inside a non-raw literal | No; the backslash and the line break are both removed | Leading spaces on the next line are kept | Yes |
| Single-line literal with explicit \n | Only where \n is written | No | Yes |
In this context, a "transformation" means converting text into a form Python can parse. That conversion changes the stored characters, not just how they are displayed. Escape sequences such as \n are turned into real newline characters when the code is compiled. Printing a string shows the real lines. Calling repr() shows the escaped form. Both describe the same value.
Triple-quoted strings capture everything between the quotes
A newline that comes right after the opening quotes is part of the string. So is any indentation used to line the text up with the surrounding code. A backslash at the end of the first line suppresses the leading newline.
text = """\
First line
Second line
"""
print(repr(text))
# 'First line\nSecond line\n'
Inside a function, the indentation that makes the code readable also ends up in the value:
def usage():
return """
Usage: tool [options]
-h show help
"""
print(repr(usage()))
# '\n Usage: tool [options]\n -h show help\n '
Removing indentation: textwrap.dedent and inspect.cleandoc
textwrap.dedent removes the leading whitespace that every non-blank line has in common. Relative indentation is kept. Lines that contain only whitespace are normalized to empty lines. Tabs and spaces both count as whitespace, but they are not treated as equal. A block that mixes them may therefore not be dedented the way it looks in an editor.
import textwrap
def usage():
return textwrap.dedent("""\
Usage: tool [options]
-h show help
""")
print(repr(usage()))
# 'Usage: tool [options]\n -h show help\n'
inspect.cleandoc follows docstring conventions. It removes leading and trailing blank lines and strips the first line's leading whitespace. It also removes the indentation shared by the remaining lines and expands tabs. It suits docstring-like text. It is less suitable when a leading or trailing blank line is meaningful. From Python 3.13, the compiler strips common leading indentation from docstrings stored in doc. That change applies to docstrings only, not to other string literals.
Adjacent literals: wrapped source, single-line value
String literals placed next to each other are joined at compile time. Inside parentheses they can span several source lines without any continuation characters. No separator is added between pieces, so any spaces or newlines have to be written explicitly.
message = (
"The configuration file could not be read, "
"so default settings were applied."
)
print(repr(message))
# 'The configuration file could not be read, so default settings were applied.'
Leaving out the trailing space in one piece silently joins two words, and the code will not raise an error. There is also a practical cost when searching. A text search for the full message will not find it in the source, because the phrase is split across literals.
Escaping existing text into a Python literal
When you paste existing text into a literal, backslashes and quotes need attention. In a normal literal, a backslash starts an escape sequence. A Windows-style path such as C:\temp\new therefore turns into a tab and a newline. From Python 3.12, unrecognized escape sequences such as \d produce a SyntaxWarning, where earlier versions emitted a DeprecationWarning. A reliable way to get a valid single-line literal for arbitrary text is to read the text into a variable and print its repr().
original = r'C:\temp\new "draft"'
print(repr(original))
# 'C:\\temp\\new "draft"'
- Raw strings keep backslashes, but a raw literal cannot end with a single backslash, so r"C:\temp" is a syntax error.
- In a raw string, a backslash before a quote stops the quote from ending the literal, but the backslash itself stays in the value.
- A triple-quoted literal can hold single and double quotes freely, except for a run of three quotes matching the delimiter.
- f-strings can also be triple-quoted. From Python 3.12, expressions inside them may reuse the same quote type and contain backslashes.
Line endings in source and output
The language reference accepts the standard line terminators regardless of platform. In normal use, a triple-quoted literal stores line breaks as \n even when the source file uses Windows line endings. The output side is separate. Writing that string to a file opened in text mode on Windows translates \n to the platform line ending unless newline is specified when the file is opened. If the output must match a particular line-ending convention, set that explicitly rather than relying on the literal.
Will the result survive copying and sharing?
The string value itself is ordinary text. Printed output copies the same way as any other plain text, and the literal adds no special characters of its own. The risk lies in the source code, because everything inside triple quotes is significant.
- Editors configured to strip trailing whitespace on save will change the content of a triple-quoted literal that relies on trailing spaces.
- Re-indenting a pasted block, or converting between tabs and spaces, changes the stored value and can change how textwrap.dedent behaves.
- Text copied from formatted documents may bring along non-breaking spaces, zero-width characters or typographic quotes. Inside the literal these are kept as-is, and if they replace the delimiters the code will not parse.
- Some editors and messaging tools replace straight quotes with typographic ones. Whether a particular destination does this has to be checked in that destination.
When exact characters matter, check the value with repr() after pasting. When sharing code that contains significant whitespace, send it as a file or as a code block rather than inline prose. If the same text must be readable outside Python, also keep a plain-text copy, for example the printed output.
Editing, review and accessibility
Triple-quoted blocks are easy to read and edit in place because the source matches the output. Adjacent literals are easier to keep within line-length limits, but they are harder to search and easier to break with a missing space. The escaped single-line form produced by repr() is precise but hard to proofread for long text. No evidence was supplied on how particular screen readers or assistive tools announce escape sequences or long literals in code. For text shown to end users, what matters is the final string, not the literal syntax used to build it.
When plain text is the better choice
Keep text out of Python literals when it is long or edited by people who do not work in the codebase. The same applies when it must be translated or must match an external file byte for byte. In those cases, store it in a plain-text or template file and load it at runtime. That separates content edits from code changes and avoids escaping entirely. Literals remain the practical choice for short, stable text that belongs with the code using it.
Evidence gaps
This review relies on documented Python language and standard-library behavior. No product-specific measurements, performance figures or test results were supplied. Behavior in specific editors, formatters, chat tools and assistive technologies was not tested here and should be checked in the environment where the code or text will be used.