Python multiline strings
last modified November 19, 2026 Python 3.15
In this article we show how to write multiline and raw string literals in Python.
A string literal is the text of a string written in source code. Ordinary
literals in single or double quotes must fit on one line. For longer text
Python has triple-quoted strings and the implicit joining of adjacent
literals. Raw strings, marked with an r prefix, turn off the
processing of backslashes. The basic quoting rules and escape sequences are
introduced in Python string; multiline
f-strings are shown in Python f-string.
Triple-quoted strings
A string in triple quotes, """ or ''', can span
several lines.
#!/usr/bin/python
poem = """The falcon flies
over 'quiet' hills
and "silent" lakes"""
print(poem)
print(poem.count('\n'), len(poem.splitlines()))
The line breaks in the source become newline characters in the string. Single and double quotes can be used inside without escaping. The string has two newlines and three lines.
$ python triple_quotes.py The falcon flies over 'quiet' hills and "silent" lakes 2 3
Newlines at the edges
Text placed on the lines after the opening quotes and before the closing ones gets extra newlines.
#!/usr/bin/python with_newlines = """ first line second line """ without = """\ first line second line""" print(repr(with_newlines)) print(repr(without))
The first string starts and ends with a newline. In the second, a backslash at the end of the first line joins it with the next line, so no newline is added; the closing quotes follow the text directly.
$ python edge_newlines.py '\nfirst line\nsecond line\n' 'first line\nsecond line'
Indentation in code
A triple-quoted string inside a function is usually indented with the code. The indentation becomes part of the string.
#!/usr/bin/python
import textwrap
def usage():
text = """
Usage: backup [options] SOURCE
-v verbose output
-n dry run
"""
return text
print(repr(usage()))
print(textwrap.dedent(usage()).strip('\n'))
The repr output shows the eight leading spaces of each line.
The textwrap.dedent function removes the whitespace common to all
lines and keeps the relative indentation of the options. The
strip('\n') call removes the newlines at the edges.
$ python indented.py '\n Usage: backup [options] SOURCE\n -v verbose output\n -n dry run\n ' Usage: backup [options] SOURCE -v verbose output -n dry run
dedent and cleandoc
When the text starts right after the opening quotes, the first line has no
indentation and dedent finds nothing in common to remove.
#!/usr/bin/python
import inspect
import textwrap
text = """Usage: backup [options] SOURCE
-v verbose output
-n dry run
"""
print(textwrap.dedent(text))
print(inspect.cleandoc(text))
The dedent function returns the string unchanged. The
inspect.cleandoc function, made for docstrings, ignores the first
line when it computes the indentation and also removes the blank lines at the
start and the end. Here it removes all indentation, because the two option
lines have the same indentation.
$ python cleandoc.py
Usage: backup [options] SOURCE
-v verbose output
-n dry run
Usage: backup [options] SOURCE
-v verbose output
-n dry run
Adjacent string literals
String literals separated only by whitespace are joined into one string. Inside parentheses they can be placed on separate lines.
#!/usr/bin/python
message = ('This message is too long to fit on one line, '
'so we split it into several literals; '
'Python joins them at compile time.')
print(message)
sql = ('SELECT id, name '
'FROM users '
'WHERE active = 1')
print(sql)
user = 'Jane'
print('Hello, ' f'{user}' '!')
The joining happens at compile time, so it costs nothing at run time. Unlike a triple-quoted string, it adds no newlines and no indentation; we must remember the spaces at the end of each part. Ordinary literals and f-strings can be mixed.
$ python adjacent.py This message is too long to fit on one line, so we split it into several literals; Python joins them at compile time. SELECT id, name FROM users WHERE active = 1 Hello, Jane!
A missing comma
The implicit joining has a downside: a forgotten comma in a list of strings is not a syntax error.
#!/usr/bin/python
colors = [
'red',
'green'
'blue',
]
print(colors)
print(len(colors))
The literals 'green' and 'blue' are joined, and the
list has two items instead of three. A trailing comma after the last item
makes such mistakes easier to spot, and some linters can be configured to
report implicit concatenation inside lists.
$ python missing_comma.py ['red', 'greenblue'] 2
Raw strings
In a raw string, a backslash is an ordinary character. Raw strings are used for regular expressions and Windows paths.
#!/usr/bin/python
import re
print('C:\new\table')
print(r'C:\new\table')
print(len('\n'), len(r'\n'))
print(re.findall(r'\b\d{3}\b', 'codes 123 4567 89 404'))
print(r'\d' == '\\d')
In the ordinary string, \n and \t are a newline and
a tab, which spoil the path. The raw string keeps the backslashes, so
r'\n' has two characters. In the regular expression, the raw
string passes \b to the re module as a word
boundary; without the prefix, \b would be a backspace character.
See Python regular expressions.
$ python raw_strings.py C: ew able C:\new\table 1 2 ['123', '404'] True
Invalid escape sequences
A backslash followed by a character that does not form an escape sequence is kept in the string, but Python warns about it.
#!/usr/bin/python pattern = '\d+' print(pattern)
The \d sequence is not an escape, so the string contains a
backslash and a d. Since Python 3.12, the compiler emits a
SyntaxWarning, and a future version will make it an error. The
fix is a raw string, r'\d+', or a doubled backslash. The warning
is shown when the file is compiled, so it does not appear again when Python
uses the cached bytecode.
$ python invalid_escape.py /home/user/python/invalid_escape.py:3: SyntaxWarning: "\d" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\d"? A raw string is also an option. pattern = '\d+' \d+
The trailing backslash
A raw string cannot end with an odd number of backslashes. A backslash still escapes a quote, even though it stays in the string.
#!/usr/bin/python
from pathlib import PureWindowsPath
source = r"folder = r'C:\temp\'"
try:
compile(source, 'test', 'exec')
except SyntaxError as e:
print('error:', e.msg)
print(r'C:\temp' + '\\')
print('C:\\temp\\')
print(len(r'\''), r'\'')
print(PureWindowsPath(r'C:\temp') / 'notes.txt')
We compile the faulty line with the compile function to show the
error message; in a source file the error stops the whole program. In
r'C:\temp\', the last backslash escapes the closing quote, so the
string never ends. We append the backslash as an ordinary string or double all
the backslashes. The fourth line shows that r'\'' is a valid
string of two characters. For paths, pathlib adds the separators
itself.
$ python trailing_backslash.py error: unterminated string literal (detected at line 1); perhaps you escaped the end quote? C:\temp\ C:\temp\ 2 \' C:\temp\notes.txt
Named Unicode characters
The \N{...} escape inserts a character by its Unicode name.
#!/usr/bin/python
import unicodedata
print('\N{EM DASH} \N{GREEK SMALL LETTER ALPHA} \N{EURO SIGN}')
print('caf\N{LATIN SMALL LETTER E WITH ACUTE}')
print('\u00e9' == '\N{LATIN SMALL LETTER E WITH ACUTE}' == '\xe9')
for c in '€α😀':
print(f'{c} U+{ord(c):04X} {unicodedata.name(c)}')
print(unicodedata.lookup('SNOWMAN'))
A name is easier to read than a code such as \u00e9, and all
three escapes in the third line give the same character. The
unicodedata.name function returns the name of a character, and
lookup finds a character by its name. Named escapes are processed
in ordinary strings only; in a raw string \N stays as it is.
$ python named_chars.py — α € café True € U+20AC EURO SIGN α U+03B1 GREEK SMALL LETTER ALPHA 😀 U+1F600 GRINNING FACE ☃
A letter template
In the last example we build a reply to a customer message from a multiline template.
#!/usr/bin/python
import textwrap
TEMPLATE = textwrap.dedent("""\
Hello {name},
you wrote:
{quoted}
{answer}
Best regards,
Support team""")
def reply(name, original, answer):
quoted = textwrap.indent(original.strip(), '> ')
return TEMPLATE.format(name=name, quoted=quoted, answer=answer)
original = """
My order 1042 has not arrived yet.
Could you check it, please?
"""
print(reply('Jane', original, 'The parcel was shipped on Monday.'))
The template is dedented once, when the module is loaded. The order matters:
if we inserted the quoted message first, its lines would have no indentation
and dedent would remove nothing. The textwrap.indent
function adds the > prefix to each line of the original
message. Because the template is not an f-string, we fill it with
format.
$ python letter.py Hello Jane, you wrote: > My order 1042 has not arrived yet. > Could you check it, please? The parcel was shipped on Monday. Best regards, Support team
Source
String and bytes literals – Python documentation
textwrap.dedent – Python documentation
In this article we have written multiline and raw strings in Python. See also Python string, Python f-string, Python split string, Python comments and docstrings, and Python lexical structure.
Author
List all Python tutorials.