escape sequence in python

ESCAPE SEQUENCES IN PYTHON


An escape sequence is a combination of characters that has a meaning other than the literal characters contained in it. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler.
Here is the table for Python escape sequences:-
S.No.
ESCAPE SEQUENCE
DESCRIPTION
1.
\\
Prints backslash
2.
\’
Prints  single quote
3.
\”
Prints double quote
4.
\a
Makes beep sound
5.
\b
Backspace-removes previous character
6.
\f
Formfeed
7.
\n
Newline
8.
\r
Carriage return
9.
\t
Horizontal tab
10.
\v
Vertical tab
11.
\uxxxx
Returns character with hexadecimal value xxxx
12.
\ooo
Returns character with octal value ooo
Some Examples:

1. \\
Suppose you want to print a "\" in your string.For example consider the code,
str='A backslash "\" is used in escape sequences'
print(str)

Output:
A backslash "" is used in escape sequences

Now to print “\” you should escape it with a '\'. So now write the following code

str='A backslash "\\" is used in escape sequences'
print(str)

Output:
A backslash "\" is used in escape sequences

2. \’ 

It is used to print a single quote in a single quoted string
Example
To print the string ‘Ankita’s Pen’
Write

print('Ankita\'s pen')
Output:
Ankita’s pen

3. \” 

It is used to print a double quote in a double quoted string
Example
print("python is an \"easy to learn language\"")
output:
python is an "easy to learn language"

4. \b 

Removes previous character

For Example,
print('alpham\bmall')

Output:

alphamall

5. \n

Introduces new line
print(“hello\nworld”)
Output
hello
world

6. \r 

Moves all characters after \r to the beginning of the line while overriding same number of characters moved.
Example
print(“pratham\rsing”)
Output:
singham
Explanation:
sing replaces “prat”

7. \t 
print(“hello\tworld”)
Output:
hello world

Comments

Popular posts from this blog

working with python IDLE

Data Types in Python