When you put text inside quotes in Python, like "Hello", Python treats it as text. This type of text is called a string. We’ll learn more about strings later.
Sometimes you need to use a special character inside a string. For example, what if you want to use double quotes inside a string that already uses double quotes?
This won’t work:
print("This will give "error")Python doesn't know where the string ends.
That's where escape sequences come in.
An escape sequence starts with a backslash (\) followed by a character.
For example:
print("This will run without any \"error\"")
# Output: This will run without any "error"The \" tells Python that the double quote is part of the string, not the end of it.
Common Escape Sequences
-
\\- Backslash: The backslash is used to create escape sequences. If you want to print an actual backslash, you need to write two backslashes.print("This is a backslash: \\") # Output: This is a backslash: \You’ll often see backslashes in file paths, especially on Windows.
For example:
print("C:\new_folder")Here,
\nis treated as a new line because\nis an escape sequence.To print the actual backslash, you need to escape it:
print("C:\\new_folder") # Output: C:\new_folder -
\'- Single Quote: Use\'when you need a single quote inside a string surrounded by single quotes.print('This is a \'single quote\'') # Output: This is a 'single quote'However, you can often avoid the escape by using double quotes:
print("This is a 'single quote'") -
\"- Double Quote: Use\"when you need a double quote inside a string surrounded by double quotes.print("This is a \"double quote\"") # Output: This is a "double quote"You can also use single quotes around the string:
print('This is a "double quote"') -
\n- New Line:\nmoves the following text to a new line.print("Line 1\nLine 2") # Output: # Line 1 # Line 2 -
\t- Tab:\tadds a tab space.print("First\tSecond") # Output: First SecondThe exact spacing can depend on where the text is displayed.
-
\b- Backspace:\brepresents a backspace character.print("Hello\bWorld")Its visible effect can depend on the terminal or environment where the output is displayed, so you don't need to worry about using it for now.
-
\r- Carriage Return:\rmoves the cursor back to the beginning of the current line.print("Hello\rWorld")\rmoves the cursor back to the beginning of the current line. In many terminals, the text that follows can overwrite the text already there.You may see
\rused in things like progress indicators and command-line output.
👉 Next tutorial: Variables in Python