Escape Characters
Escape characters in Python allow us to include special characters in a string, such as quotation marks, newlines, tabs, or backslashes, which would otherwise be difficult to represent directly.
Single/Double Quote: used to insert single/double quotes in the string.
Example:
str1 = "He was \"Flabbergasted\"."
str2 = 'He was \'Flabbergasted\'.'
print(str1)
print(str2)Output:
He was "Flabergasted".
He was 'Flabergasted'.
New Line: inserts a new line wherever specified.
Example:
str1 = "I love doing Yoga. \nIt cleanses my mind and my body."
print(str1)Output:
I love doing Yoga.
It cleanses my mind and my body.
Tab: inserts a tab wherever specified.
Example:
str2 = "Hello \t\tWorld \t!!!"
print(str2)Output:
Hello World !!!
Backspace: erases the character before it wherever it is specified.
Example:
str2 = "Hello \bWorld !!!"
print(str2)Output:
Hello World !!!
Backslash: used to insert a backslash into a string.
Example:
str3 = "What will you eat? Apple\\Banana"
print(str3)Output:
What will you eat? Apple\Banana