Python online course

Python Escape Characters in Strings

Learn how Python interprets backslashes in strings, including newline, tab, quotation mark, backslash, raw string, and repr() examples.

A string is an ordered sequence of characters. In Python, a string literal is text written directly in source code and enclosed in quotation marks, such as "hello" or 'hello'.

Python gives the backslash character a special role inside ordinary string literals. A backslash followed by another character is called an escape sequence. Python interprets the combination as a special character or behavior.

For example, the source code "one\ntwo" contains the two-character combination backslash-and-n, but the resulting string contains a newline between one and two. This distinction between the source-code representation and the resulting string value is central to understanding escapes.

The Backslash Character

The backslash (\) is the escape character in ordinary Python strings. It introduces an escape sequence. To place one literal backslash in the resulting string, generally write two backslashes in the source code.

path = "C:\\nature"
print(path)
C:\nature

The two backslashes in the literal are interpreted as one literal backslash. This rule matters particularly for Windows-style paths. In the following example, the characters \n are not treated as a path separator followed by the letter n; Python interprets them as a newline.

print("C:\nature")

The output is effectively:

C:
ature

Here, \n moves the output to a new line, so the intended path is not preserved. Use "C:\\nature" or a suitable raw string instead.

The Newline Escape Sequence

\n represents a newline, which is a line-break character. When print() encounters it, subsequent output starts on the next line.

message = "First line\nSecond line"
print(message)
First line
Second line

An escape sequence usually represents one character in the resulting string. Thus, \n typically becomes one newline character, while \\ becomes one literal backslash.

Escaping Quotation Marks

The quotation marks around a string are its delimiters. A delimiter marks where the string literal begins and ends. If a quote inside the string matches the delimiter, Python may interpret it as the end of the string.

Escape a matching double quote with \":

print("She said: \"I don't love you anymore\"")
She said: "I don't love you anymore"

Similarly, escape a matching single quote with \':

print('It\'s time to learn Python')
It's time to learn Python

You can often avoid escaping by choosing the other quote style. A double quote can appear normally inside a single-quoted string:

print('She said: "I do not love you anymore"')

If an embedded quote prematurely ends a string, Python cannot parse the source and raises a SyntaxError.

Common Python Escape Sequences

Sequence in source codeResulting character or behaviorTypical useExample
\\One literal backslashWindows paths and escaped backslashes"C:\\temp"
\'One literal single quoteSingle-quoted strings containing an apostrophe'It\'s ready'
\"One literal double quoteDouble-quoted strings containing quotation marks"Say \"hello\""
\nNewlineStarting output on a new line"A\nB"
\tHorizontal tabSpacing columns of formatted text"Name\tScore"
\rCarriage returnMoving the cursor to the beginning of a line"Loading\rDone"
\bBackspaceMoving the cursor back one position"ab\bc"
\fForm feedLegacy page or text-control behavior"Page\fNext"
\vVertical tabVertical spacing in some text environments"Top\vBottom"
\aBell or alert characterAlerting the terminal, when supported"Warning\a"
\0Null characterIncluding a character with numeric value zero"A\0B"

The visible result of control characters such as \r, \b, \f, \v, and \a depends on the terminal, console, text editor, or other output environment. Their underlying characters are still part of the string even when the display does not show an obvious effect.

Tabs and Newlines Together

print("Name\tScore\nAda\t95")
Name    Score
Ada     95

A tab advances to a tab stop, so the exact visual spacing can vary. A newline begins a separate output line.

Raw String Literals

A raw string is a string literal prefixed with r or R. It treats most backslashes as literal characters instead of processing ordinary escapes. Raw strings are convenient for many Windows paths and regular expressions.

print(r"C:\nature")
C:\nature

In this example, the backslash remains a backslash and the characters n remain the letter n.

Literal formHow backslashes are handledBest use caseImportant limitation
Ordinary quoted stringBackslash sequences are interpretedNewlines, tabs, quotes, and controlled charactersBackslashes intended literally usually need doubling
Raw string prefixed with rMost backslashes remain literalMany paths and regular expressionsIt cannot end with an odd number of backslashes, and matching delimiters still need to be handled

Raw strings do not remove all lexical restrictions. For example, a raw string cannot end with one trailing backslash:

r"C:\folder\"

The final backslash would escape the closing quote at the source-code level. A raw string also cannot contain an unescaped matching delimiter. If a raw path must end with a backslash, use an ordinary string with an escaped final backslash, concatenate a separate backslash, or choose another construction.

Inspecting String Values with print() and repr()

print() renders the string for a reader. It applies the effects of newline and tab characters, so its output may look different from the literal typed in source code.

repr() returns a diagnostic representation of an object. For strings, it generally exposes special characters using escape notation, making it useful for checking whether a value contains an actual newline or the two ordinary characters backslash and n.

value = "C:\\nature\nplants"
print(value)
print(repr(value))
C:\nature
plants
'C:\\nature\nplants'

The first call renders the newline. The second call shows the newline as \n and the literal backslash as \\ in the representation. Interactive Python output often uses a representation similar to repr(), which is why entering a variable at the interactive prompt can look different from calling print().

Escaped Characters and String Indexing

After Python creates a string, escaped content participates in normal string operations. You can index the string to access individual characters.

path = "C:\\nature"
print(path[1])
print(path[2])
:
\

The colon and the literal backslash are individual characters in the resulting string. The source notation \\ occupies two characters in the source code but produces one character in the string. This is also why an escape such as \n normally takes one index position after the string has been created.

For more practice with character positions, see Access Individual Characters and Python strings.

Troubleshooting Escape Sequences

  • A path such as C:\nature prints on two lines: Python read \n as a newline. Use "C:\\nature" or r"C:\nature" when the raw-string limitations do not apply.
  • Quotation marks cause a SyntaxError: An internal quote probably matches the string delimiter. Escape that quote or use the opposite quote style.
  • A tab or newline appears when literal characters were expected: A sequence such as \t or \n was interpreted. Write the backslash as \\ or use an appropriate raw string.
  • A raw path fails near its final quote: The raw string probably ends with a single trailing backslash. Avoid ending a raw string with an odd number of backslashes.
  • Output differs from the typed literal: print() renders control characters. Use repr(value) to inspect the stored value.

Practice and Exam Notes

  1. Count the backslashes in the source code, then determine the resulting characters.
  2. Remember that \n is one newline character, while \\ is one literal backslash.
  3. Check which quote character delimits the string before deciding whether an embedded quote needs escaping.
  4. Use print() to observe rendered output and repr() to inspect the representation.
  5. For a Windows path containing a segment such as \n, double the backslash or use a raw string that does not end with an odd number of backslashes.