VMware ESXi and vSphere Cluster Management

Python Escape Characters in Strings

Learn how Python escape characters work, including newline, tab, quotes, literal backslashes, raw strings, and common string errors.

A string is a sequence of characters. In Python source code, a string is usually created with a string literal: quoted text such as "hello" or 'hello'.

Some character combinations inside a string literal have special meanings instead of appearing literally. Python uses the backslash character (\) as an escape character. A backslash changes how the following character or sequence is interpreted.

An escape sequence is a backslash-based sequence such as \n or \t. Some escape sequences control formatting, while others produce visible characters such as quotes or backslashes.

Why escape characters are needed

String delimiters tell Python where a string starts and ends. Backslashes let you include special characters without confusing Python's parser, or insert formatting actions into the string value.

  • Formatting escape: \n inserts a newline and \t inserts a tab.
  • Visible-character escape: \\ produces one visible backslash, while \" produces a visible double quote.

The source representation and the resulting string are related but are not always identical. For example, the two source characters backslash and n become one newline character in the string.

The newline escape sequence

\n represents a newline, which is a line break. The print() function displays the text after that line break on the next output line.

print("first line\nsecond line")

Output:

first line
second line

This behavior can be surprising in Windows-style paths. Consider this literal:

print("C:\nature")

In the source, the path appears to contain \n between the backslash and the word nature. Python recognizes that pair as the newline escape sequence. The output is therefore split into two lines: C: followed by ature. The n has been used as part of the escape sequence, so it is not printed as the letter n.

Writing a literal backslash

To place one visible backslash in an ordinary string literal, write two backslashes in the source code: \\.

print("C:\\nature")

Output:

C:\nature

The first backslash escapes the second one. Together, \\ creates a string containing one literal backslash. This is why the source code has more backslashes than the printed result.

Escaping quote characters

A quote matching the string delimiter normally marks the end of a string. Consequently, an unescaped double quote inside a double-quoted string causes invalid syntax:

message = "She said: "Hello""

Python sees the second double quote as the end of the string, so the remaining text cannot be parsed correctly. The usual result is a SyntaxError.

Use \" to include a literal double quote inside a double-quoted string:

print("She said: \"I love you very much.\"")

Output:

She said: "I love you very much."

The equivalent rule applies to single quotes. Inside a single-quoted string, write \' for a literal single quote:

print('It\'s a useful example.')

Choosing string delimiters

Python permits both single-quoted and double-quoted strings. Choosing the delimiter that does not occur in the text can avoid escaping quotation marks.

sentence = 'She said: "Hello"'
print(sentence)

Here, the outer delimiters are single quotes, so the double quotes are ordinary characters in the string.

You can also use double quotes around text containing an apostrophe:

sentence = "It's a useful example."

Changing delimiters does not remove the need to escape literal backslashes. A backslash can still begin an escape sequence regardless of whether the string uses single or double quotes.

Common Python escape sequences

Sequence written in source codeMeaningEffect when printedTypical use
\\Literal backslashOne visible backslashWindows-style paths or backslash-based text
\nNewlineMoves following output to a new lineMulti-line messages
\tHorizontal tabMoves output to the next tab positionSimple columns
\rCarriage returnMoves the cursor to the beginning of the current lineSome terminal and text-processing operations
\'Literal single quoteOne visible single quoteSingle-quoted strings containing apostrophes
\"Literal double quoteOne visible double quoteDouble-quoted strings containing quotation marks

For example, \n and \t affect formatting, while \\, \', and \" represent visible characters.

Using newline and tab formatting

Escape sequences can make small reports readable:

print("Name\tValue\ncolor\tblue")

Typical output is:

Name   Value
color  blue

The exact horizontal spacing after a tab depends on the environment and the current cursor position.

Ordinary strings and raw strings

Ordinary string literals process recognized escape sequences. A raw string is prefixed with r and generally treats backslashes as literal characters.

ordinary_path = "C:\\nature"
raw_path = r"C:\nature"

print(ordinary_path)
print(raw_path)

Both variables represent the same path-like text and print:

C:\nature
C:\nature

Raw strings are useful for many backslash-heavy paths, regular expressions, and other patterns. They do not make every character completely unrestricted: quotes still need appropriate handling, and a raw string cannot end with an odd number of backslashes.

path = r"C:\"

The final backslash can interfere with the closing quote, so this is invalid. Use an ordinary string with an escaped backslash, or construct the final backslash separately:

path = "C:\\"
path = r"C:" + "\\"

Comparing ways to represent special text

Desired textNormal string literal optionAlternate delimiter optionRaw string suitability or limitation
A file path with backslashes"C:\\nature"Changing quote type does not change backslash rulesr"C:\nature" is convenient; it cannot end with an odd number of backslashes
Text containing double quotes"She said: \"Hi\""'She said: "Hi"'Possible, but quotes still require appropriate delimiters or escaping
Text containing single quotes'It\'s ready'"It's ready"Possible, but the closing quote must still be handled correctly
A value ending in a backslash"C:\\"Delimiter choice does not solve the final-backslash issueRaw strings cannot end with an odd number of backslashes

Reading errors and checking output

Two different problems can look similar:

  • A SyntaxError means Python could not parse the source code. Broken quotation marks are a common cause.
  • Valid code can still produce unexpected output when a recognized escape sequence inserts a newline, tab, or carriage return.

When debugging, inspect both the source literal and the value that Python created. print() shows formatting characters as actions, while repr() displays an escaped representation that makes those characters easier to see.

text = "C:\nature"
print(text)
print(repr(text))

The first call prints a line break. The second displays a representation similar to 'C:\nature', making the newline escape visible in the representation.

Troubleshooting common escape-character problems

A path prints on two lines

The likely cause is a backslash followed by n, which Python interpreted as \n. Double the backslash in a normal string or use a suitable raw string:

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

Python reports a SyntaxError after quotation marks are added

An embedded quote probably matches the outer string delimiter and prematurely closes the literal. Escape it or choose the other delimiter:

print("She said: \"Hello\"")
print('She said: "Hello"')

A raw string cannot represent the intended final character

A raw string ending with an odd number of backslashes conflicts with parsing of its closing quote. Use a normal string with escaped backslashes, or add the final backslash through another valid string.

Output contains unexpected tabs or line breaks

Review every backslash sequence. If the backslash should be visible rather than interpreted, use \\ in an ordinary string or consider raw string notation where its limitations are acceptable.

Key points

  • The backslash is Python's escape character in ordinary string literals.
  • \n creates a newline, and \t creates a tab.
  • Write \\ to produce one visible backslash.
  • Escape a quote that matches the outer delimiter, or select the opposite delimiter.
  • Raw strings reduce backslash escaping for many patterns and paths, but cannot end with an odd number of backslashes.
  • Use repr() alongside print() when you need to distinguish visible formatting from the stored string value.

For connected practice, continue with Python escape characters.