In Python, a string cannot contain some characters (like “, \) directly. Such characters must be escaped by placing a backslash before them. Below are some examples:
Python Escape Sequence Examples
We are giving the following example to print a string, as what’s your age?
print('what's your age')
SyntaxError: invalid syntax
Here Python gets confused as to where the string starts and ends. It is needed to clearly specify that the single quote does not indicate the end of the string. This indication can be given with the help of an escape sequence.
The following example is printing a string using an escape sequence.
print ('what's your age?')
what's your age?
When specifying a string, if a single backslash (\) at the end of the line is added, it indicates that the string is continued in the next line, but no newline is added otherwise.
print("I have obtained 80% marks.\ But you have obtained 90% marks in Python.")
I have obtained 80% marks.But you have obtained 90% marks in Python.
Actually, an Escape sequence is a combination of characters translated into another character or a sequence of characters that may be difficult or impossible to represent directly.
The following Escape Sequences are used in Python.
1. Escape Sequence \\ is used to print Backslash.
The following example is printing Backslash.
2. Escape Sequence ‘ is using to print single-quote.
Now we are giving an example to print a single-quote.
3. We can print double-quote with the help of Escape Sequence “.
Here we are giving an example to print double-quote.
4. Escape Sequence \n is using to print a newline character.
The following example is printing a newline character.
5. Escape Sequence \t helps us to print a horizontal tab.
Now the following example is using to print a horizontal tab.
Welcome to Kolkata
6. Escape Sequence \0 prints octal value.
Here the given an example is printing octal “.”
7. Escape Sequence \x is used to print hex value
Now we are giving an example to print a hex value.
8. Escape Sequence \b is using to delete a character.
Here We are giving an example for using Escape Sequence \b
Hereafter, printing hello, a backspace is deleting the last character o
, and then the world is printing. So, the final result is “hellworld.”