Python escape characters

Certain characters are difficult to type in a string. For example: we know that a string is defined in double or single code but what will we do if we want that a string defined in double quotes should have double quotes? There are many such difficult to type of characters which can be encoded into a string using a backslash (\) character. This tutorial is dedicated to that.

New line character – \n

What would you do if you want to insert an end of line or line break in a string variable? Well, here is a solution: use \n as shown in the example below:

var1 = "Welcome \n John"
print (var1)

Download the code Run the code

How to add double quotes in a string variable that is defined in double quotes

If you want the string to have the value of: welcome “John” then you will require to insert \” before John as shown in the code below:

var1 = "Welcome \"John\""
print (var1)

Download the code Run the code

Similarly a single quote can be added with the help of \’.

var1 = 'Welcome \'John\''
print (var1)

Download the code Run the code

ASCII bell – \a

‘\a’ is used to produce a motherboard beep. Try out the following code to see how the output displays in python shell.

var1  =  "Welcome \a John\a"
print (var1)

Download the code  Run the code

ASCII backspace – \b

ASCII backspace can be inserted in the string literal with the help of ‘\b’. Execute the following code to see the output in Python shell.

var1 = "Welcome \b John\b"
print (var1)

Download the code Run the code

ASCII form feed \f

ASCII formfeed ‘\f’, skips to the start of the next page and is generally where the output goes to the printer.

var1 = "Welcome \f John"
print(var1)

Download the code Run the code

Horizontal tab – \t

As the name suggests \t adds a horizontal tab in the string variable.

var1 = "Welcome John"
var2 = "\tWelcome John"
print (var1)
print (var2) 

Download the code Run the code

<<< Python stringsPython string special operators >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .