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.
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)
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)
Similarly a single quote can be added with the help of \’.
var1 = 'Welcome \'John\'' print (var1)
‘\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)
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)
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)
As the name suggests \t adds a horizontal tab in the string variable.
var1 = "Welcome John" var2 = "\tWelcome John" print (var1) print (var2)