PythonPython StringsPython string literals
How do you create strings using single, double, and triple quotes?
Question 61 of 88 · Updated
On this page
- 1. Single and double quotes
- 2. Escaping delimiters and special characters
- 3. Triple quotes and multiline text
- 4. Controlling multiline indentation
- 5. Raw strings: when backslashes are literal
- 6. Adjacent string literals
- 7. Unicode literals and escape notation
- 8. Triple quotes and docstrings
- 9. Common syntax errors
- 10. Practical guidelines
- Frequently asked questions
- Are single and double quotes different string types?
- When should I use triple quotes?
- Are triple-quoted strings raw strings?
- Are quotes stored inside a string?
- Can I write a raw string ending with a single backslash?
- Can adjacent strings use different quotation styles?
- Interview-ready answer
- Official references
Python creates ordinary text strings by enclosing source text in matching single quotes, double quotes, or groups of three matching quotes. All three forms produce the same built-in str type. The choice of delimiter changes how the source is written, not the type or ordinary value semantics of the resulting string.
Single and double quotes are convenient for short text. Triple quotes allow literal line breaks and are commonly used for multiline text and docstrings. Escape sequences and literal prefixes further determine how the source is interpreted.
1. Single and double quotes#
PYTHONa = 'Python' b = "Python" print(a == b, len(a)) print("It's ready") print('She said "yes"')
Output:
True 6
It's ready
She said "yes"The first two literals represent identical sequences of six code points. The surrounding delimiters do not become part of either string.
Choose double quotes when the content contains apostrophes, or single quotes when the content contains double quotation marks. This often avoids unnecessary backslashes. Python does not require one ordinary quoting style over the other; PEP 8 recommends consistency and choosing a delimiter that reduces escaping.
The empty literals '' and "" both create empty strings.
| Literal form | Typical use |
|---|---|
'text' | Ordinary short text |
"text" | Ordinary short text, especially with apostrophes |
'''text''' | Text spanning multiple source lines or containing both ordinary quote characters |
"""text""" | Multiline text and conventional docstrings |
The opening and closing delimiters must match. Ordinary single- and double-quoted literals cannot contain an unescaped physical newline.
2. Escaping delimiters and special characters#
When a string must contain its own delimiter, a backslash can escape that delimiter. Ordinary string literals also interpret recognized escape sequences.
PYTHONtext = 'It\'s "ready"' print(text) print(repr("A\nB\tC")) print(len("\\"))
Output:
It's "ready"
'A\nB\tC'
1The apostrophe in the first literal is part of the resulting text rather than its closing delimiter. The two backslashes in the last literal represent one backslash in the resulting string.
| Source escape | Meaning in an ordinary string |
|---|---|
\' | Single quote |
\" | Double quote |
\ | Literal backslash |
\n | Newline |
\t | Horizontal tab |
\r | Carriage return |
\xhh | Code point specified by exactly two hexadecimal digits |
\uhhhh | Code point specified by exactly four hexadecimal digits |
\Uhhhhhhhh | Code point specified by exactly eight hexadecimal digits |
\N{name} | Character identified by a Unicode name |
Here h denotes a hexadecimal digit, not literal source text to copy.
An escape sequence is source syntax for specifying a value; it is not necessarily the sequence of characters stored in that value. For example, an ordinary newline escape occupies one code point in the resulting string. Inspect repr when the difference between invisible whitespace and displayed backslash notation is important.
An unrecognized escape such as backslash followed by q is retained as those two characters in the tested CPython 3.13.5 runtime, but produces a SyntaxWarning. Unrecognized escapes are not a safe long-term way to express literal backslashes; use a recognized escape or an appropriate raw literal. Future Python versions may reject such sequences.
3. Triple quotes and multiline text#
PYTHONtext = """first second""" other = '''He said "yes". It's fine.''' print(repr(text)) print(other)
Output:
'first\nsecond'
He said "yes".
It's fine.Triple-quoted strings allow physical newlines in their bodies. Those newlines normally become part of the resulting text. A triple-quoted literal can contain individual single and double quote characters without escaping them, provided the content does not form an unescaped matching triple-quote delimiter.
Triple quotes do not automatically trim whitespace or disable escape processing. The indentation inside a multiline literal becomes part of the string. A newline immediately after the opening delimiter is normally included, and so is a newline immediately before the closing delimiter.
This behavior is useful for preserving document text, templates and messages, but it can introduce unwanted spaces when the literal is indented with surrounding code.
4. Controlling multiline indentation#
PYTHONfrom textwrap import dedent def message(): return dedent("""\ Status: ready Items: 2 """).rstrip("\n") print(repr(message()))
Output:
'Status: ready\nItems: 2'The backslash immediately before the physical newline in this ordinary triple-quoted literal suppresses that initial newline. The textwrap.dedent function removes common leading indentation from lines. The final rstrip call removes trailing newline characters.
The resulting string has neither the indentation used to align the function's source code nor a trailing newline. It retains the line break between the two actual content lines.
Dedent is useful when all content lines share a common indentation margin. It does not understand a document format's intended semantic indentation. In indentation-sensitive formats, preserve the relative spaces required by the format. Also avoid indiscriminately stripping spaces or line breaks from text whose exact layout is meaningful.
5. Raw strings: when backslashes are literal#
A raw string literal has an r or R prefix immediately before its opening quote. Most ordinary escape processing is disabled in raw string literals, so backslashes remain in the resulting text.
PYTHONnormal = "A\nB" raw = r"A\nB" print(len(normal), len(raw)) print(raw) print(r"C:\new\test" == "C:\\new\\test")
Output:
3 4
A\nB
TrueThe ordinary literal contains A, a newline and B. The raw literal contains A, a backslash, n and B. The two path literals represent identical strings, written with different source syntax.
The diagram concerns the specific valid newline-escape example, not all lexical rules. Raw strings are still subject to delimiter recognition. A quote can be escaped in a raw literal, but that backslash remains in its value. A raw literal cannot end with an odd number of backslashes immediately before its closing delimiter.
For paths, pathlib often provides a clearer interface for joining components. For regular expressions, raw literals can make the Python source easier to read, but the regular-expression engine still interprets its own pattern syntax. Raw quoting does not make a regex pattern literal or safe against unexpected input. The dedicated regex lesson covers that separate layer.
Triple-quoted raw strings are also supported; their physical newlines remain part of the text.
6. Adjacent string literals#
PYTHONmessage = ( "Order " 'confirmed' ) print(message) print("a" "b" == "ab")
Output:
Order confirmed
TruePython allows adjacent ordinary string literals to be concatenated as part of the source syntax, including literals using different quote styles. Parentheses allow the expression to span multiple physical lines.
Unlike a triple-quoted multiline literal, the source line break between the two separate literals here does not add a newline to the string. The space between Order and confirmed comes from the first literal's explicit trailing space.
Adjacent literal concatenation is useful for breaking long static text across source lines. It is not a general operation on variables or arbitrary expressions. Runtime concatenation and efficient combination of many fragments are covered separately.
Be careful when writing lists of strings: forgetting a comma between adjacent literals can silently concatenate them into one list element. Code review and tests should check the intended number and contents of entries.
7. Unicode literals and escape notation#
PYTHONprint("\u00e9" == "é") print("\N{LATIN CAPITAL LETTER A}", "\x42") print(len("\U0001F642"))
Output:
True
A B
1Python source can contain Unicode text directly, or use Unicode escapes to express particular code points. The first expression demonstrates that the literal code point U+00E9 and the corresponding directly written character have the same value.
The named escape specifies a character by its Unicode name. The two-digit hexadecimal escape in the example specifies U+0042. The eight-digit Unicode escape represents one emoji code point, not eight characters.
Python 3 source files use UTF-8 by default unless a supported encoding declaration specifies otherwise. This source-file encoding is distinct from the encoding used later to write a string to a file, send it across a network or communicate with an external system.
Prefixes can affect other literal semantics as well. An ordinary u-prefixed literal still represents str in Python 3; a b-prefixed literal represents bytes instead of str. An f-prefixed literal supports expression interpolation. The upcoming f-string lesson explains formatting and expression evaluation in detail.
8. Triple quotes and docstrings#
PYTHONdef status(): """Return the current status.""" return "ready" print(status.__doc__) print(status())
Output:
Return the current status.
readyA string literal appearing as the first statement of a function, class or module is recognized as its docstring when it meets the language's documentation rules. Triple double quotes are the conventional docstring style recommended by PEP 257, including for single-line docstrings.
Triple quotes by themselves do not make a literal a docstring. Assigning a multiline string to a name produces ordinary data. A standalone literal elsewhere is an expression statement, not a lexical comment.
Use a hash-prefixed comment when the intention is to annotate source code rather than create string data. The earlier comments lesson explains the distinction between comments, docstrings and ordinary string expressions.
9. Common syntax errors#
These four invalid source fragments were independently compiled and each raised SyntaxError:
| Invalid source | Reason |
|---|---|
| An opening single quote with no matching closing quote | Unterminated string literal |
| An ordinary single-quoted literal containing an unescaped physical newline | Short string delimiters do not allow that newline |
| An opening double quote followed by only a single quote at the end | Mismatched delimiters |
| A raw string with one final backslash immediately before its closing quote | The closing delimiter is not recognized as intended |
These are source-code errors, not ordinary runtime validation failures. The interpreter must successfully parse the program before it can execute the affected code.
Copying text from word processors can also introduce curly typographic quotation marks. They are not Python string delimiters. Use ordinary ASCII single or double quotation marks for the source syntax.
When a string displays unexpectedly, inspect its repr and length. That often reveals an accidental newline, tab, space or literal backslash that is difficult to see in normal printed output.
10. Practical guidelines#
- Use matching single or double quotes for ordinary text, consistently with the project's style.
- Choose the delimiter that avoids unnecessary escapes.
- Use triple quotes for genuine multiline content and conventional docstrings.
- Check the exact indentation and newline behavior of multiline literals.
- Use raw strings when preserving backslashes is useful, while respecting raw-literal closing rules.
- Use explicit Unicode escapes when a code point would otherwise be difficult to distinguish or type.
- Keep literal syntax separate from external data formats and security requirements.
Changing the quoting delimiter does not itself make an ordinary string faster or consume less memory for the same resulting value. The size and contents of the text, representation choices and interpreter behavior matter more than the original delimiter.
Do not construct executable Python source from untrusted text merely to insert quotation marks. Similarly, quoting a value in Python source does not automatically make it safe for SQL, HTML, JSON or a shell command. Use the destination format's appropriate serialization, parameterization or escaping interface.
Frequently asked questions#
Are single and double quotes different string types?#
No. Ordinary literals using either delimiter produce str values. They can represent exactly the same text.
When should I use triple quotes?#
Use them when text should span source lines, when they simplify embedded quotation marks or for the conventional spelling of docstrings. Check whether the physical newlines and indentation should be retained.
Are triple-quoted strings raw strings?#
No. Ordinary triple-quoted strings still process recognized escape sequences. A raw prefix changes that processing.
Are quotes stored inside a string?#
The delimiting quotes are not part of the string value. Quotation marks written inside the content, using an appropriate delimiter or escape, are part of that value.
Can I write a raw string ending with a single backslash?#
Not as one raw literal with that backslash immediately before the closing delimiter. Use an ordinary escaped literal, or combine valid string fragments.
Can adjacent strings use different quotation styles?#
Yes. Adjacent compatible string literals may be concatenated by Python's syntax even if their delimiters differ. This is not the same as concatenating arbitrary runtime variables.
Interview-ready answer#
In Python, single quotes, double quotes and triple quotes create ordinary str literals. Single and double quotes have equivalent value semantics and can be chosen to reduce escaping. Triple quotes allow physical newlines and are common for multiline text and docstrings, but they preserve relevant whitespace and still process ordinary escape sequences. Backslashes represent recognized escapes such as newline, tab and literal backslash; a raw prefix preserves most backslashes while still following quote-delimiter rules. The surrounding delimiters are not part of the string value. Use the form that expresses the intended text clearly and test exact whitespace and escaping when they matter.
Official references#
- Python Language Reference — String and bytes literals
- Python Language Reference — String literal concatenation
- Python Tutorial — Text
- Python Standard Library — Text sequence type
- Python Standard Library — textwrap.dedent
- PEP 8 — String Quotes
- PEP 257 — Docstring Conventions
Verification note: All eight fenced Python examples matched their documented outputs in independent namespaces on CPython 3.13.5. Four invalid-source compilation tests produced the expected SyntaxError. One additional test verified the retained unrecognized escape and its SyntaxWarning. The single fenced Mermaid flowchart was manually reviewed for the specific example. The local Mermaid CLI was unavailable, so parser-level validation and public rendering were not verified. Official links are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Language Reference — String and bytes literalsdocs.python.org
- 2.Python Tutorial — Textdocs.python.org
- 3.Python Standard Library — Text sequence typedocs.python.org
- 4.Python Standard Library — textwrap.dedentdocs.python.org
- 5.PEP 8 — String Quotespeps.python.org
- 6.PEP 257 — Docstring Conventionspeps.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design