0%

Working with Text · practice

Special Characters and Line Breaks

Some characters are difficult to place directly inside an ordinary . A quotation mark might look like the end of the string. A line break cannot be shown as a normal visible character on one line of code.

Python uses an escape sequence for these cases. An escape sequence begins with a backslash (\) and represents a character inside the string.

Put quotation marks inside a string

This double-quoted string contains double quotation marks as text:

message = "She said, \"Hello.\""
print(message)

The backslashes tell Python that the following quotation marks belong to the text. The output is:

She said, "Hello."

The backslashes are instructions in the code. They do not appear in the output.

Add a line break

The escape sequence \n represents a newline:

Try it

One string produces two output lines.

Python still stores this as one string. The newline is one character inside that sequence.

Common escape sequences

SequenceCharacter it represents
\nNewline
\tTab
\"Double quotation mark inside a double-quoted string
\'Apostrophe inside a single-quoted string
\\One literal backslash

A tab can help with simple experiments, but it is not a reliable way to build aligned page layouts. Different and content can display tabs differently.

To store a Windows-style path such as C:\courses, the backslash itself must be escaped:

path = "C:\\courses"

What will this program print?

print("one\ntwo")

Build a two-line message

Change the assigned to message. Use one string containing escape sequences so the output is exactly:

She said, "Python is fun."
Then she pressed Run.

Your string needs escaped double quotation marks and one newline. Keep the existing print(message) instruction.

Type the escape sequences yourself. If Python reports a , check each quotation mark and backslash from left to right.

Task

one to message so the output is exactly:

She said, "Python is fun."
Then she pressed Run.

Use escaped quotation marks and \n. Keep print(message).