Course
Escape Characters
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Escape Characters
In Python, a string becomes a raw string if it is prefixed with "r" or "R" before the quotation symbols. Hence 'Hello' is a normal string whereas r'Hello' is a raw string.
>>> normal="Hello">>> print (normal)Hello>>> raw=r"Hello">>> print (raw)Hello
In normal circumstances, there is no difference between the two. However, when the escape character is embedded in the string, the normal string actually interprets the escape sequence, whereas the raw string doesn't process the escape character.
>>> normal="Hello\nWorld">>> print (normal)HelloWorld>>> raw=r"Hello\nWorld">>> print (raw)Hello\nWorld
In the above example, when a normal string is printed the escape character '
\n
' is processed to introduce a newline. However, because of the raw string operator 'r' the effect of escape character is not translated as per its meaning.The newline character
\n
is one of the escape sequences identified by Python. Escape sequence invokes an alternative implementation character subsequence to "\
". In Python, "\
" is used as escape character. Following table shows list of escape sequences.Unless an 'r' or 'R' prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are
Example
The following code shows the usage of escape sequences listed in the above table
# ignore \s = 'This string will not include \backslashes or newline characters.'print (s)
# escape backslashs=s = 'The \\character is called backslash'print (s)
# escape single quotes='Hello \'Python\''print (s)
# escape double quotes="Hello \"Python\""print (s)
# escape \b to generate ASCII backspaces='Hel\blo'print (s)
# ASCII Bell characters='Hello\a'print (s)
# newlines='Hello\nPython'print (s)
# Horizontal tabs='Hello\tPython'print (s)
# form feeds= "hello\fworld"print (s)
# Octal notations="\101"print(s)
# Hexadecimal notations="\x41"print (s)
It will produce the following output
This string will not include backslashes or newline characters.The \character is called backslashHello 'Python'Hello "Python"HeloHelloHelloPythonHello PythonhelloworldAA
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.