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')
Output:
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?')
Output:
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.
For Example:
print("I have obtained 80% marks.\ But you have obtained 90% marks in Python.")
Output:
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.
print("")
Output:
\
2. Escape Sequence ' is using to print single-quote.
Now we are giving an example to print a single-quote.
print("'")
Output:
'
3. We can print double-quote with the help of Escape Sequence ".
Here we are giving an example to print double-quote.
print(""")
Output:
"
4. Escape Sequence \n is using to print a newline character.
The following example is printing a newline character.
print("Hello\nWorld")
Output:
Hello World
5. Escape Sequence \t helps us to print a horizontal tab.
Now the following example is using to print a horizontal tab.
print(“Welcome\tto Kolkata”)
Output:
Welcome to Kolkata
6. Escape Sequence \0 prints octal value.
Here the given an example is printing octal "."
print("\056")
Output:
.
7. Escape Sequence \x is used to print hex value
Now we are giving an example to print a hex value.
print("\x87")
Output:
+
8. Escape Sequence \b is using to delete a character.
Here We are giving an example for using Escape Sequence \b
print("hello\bworld")
Output:
hellworld
Hereafter, printing hello, a backspace is deleting the last character o
, and then the world is printing. So, the final result is "hellworld."
Leave a comment