Working with Text · practice
Special Characters and Line Breaks
Some characters are difficult to place directly inside an ordinary
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:
One string produces two output lines.
Python still stores this as one string. The newline is one character inside that sequence.
Common escape sequences
| Sequence | Character it represents |
|---|---|
\n | Newline |
\t | Tab |
\" | 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
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 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
Task
message so the output is exactly:
She said, "Python is fun."
Then she pressed Run.
Use escaped quotation marks and \n. Keep print(message).