The backslash, \, is used to get certain special characters, called escape characters, into your string.
There are a variety of escape characters, and here I am going to show you the most useful ones:
• \n the newline character. It is used to move text to the next line. Here is an example:
print('did you\nunderstand\n\nwhat happen\n\n\nhere')
did you understand what happen here
looking at the example above and its result you will notice that the gap between each line is different. did you notice that? Yeah! that is because we put different newline character between the sentence in our code. check the code again did you see the "\n" use once twice and three times between the sentence? so, the more you add the character the more it ommit the next line. "\n" ommit just next line, "\n\n" ommited next two line "\n\n\n\" ommited next three line etc.
• \' this is used to insert apostrophes into strings. assuming you have the following string:
myWord= 'I can't commit error' print(myWord)
This will produce an error because the apostrophe will actually end the string. You can use \' to get around this:
myWord = 'I can\'t commit error' print(myWord)
I can't commit error
Another option is to use double quotes for the string :
myWord="I can't commit error" print(myWord)
I can't commit error
• \" is similar to \' i.e you can use double quote instead of single quote for example
myWord='I can\"t commit error' print(myWord)
• \ This is used to get the backslash itself. For example:
newline = '\\n is used for newline' print(newline)
\n is used for newline
run the code. did you see the backslash? yeah! despite the fact that "\n" it self is used for newline and it is inside our code above yet it doesn't move to next line because the two backslash is interpreted and n is consider as text.
• \t the tab character this is used to give tab space.
tab_word="I \twas \tgiven \ttab" print(tab_word)
I was given tab
try to confirm the code with the result did you see the tab space between them. try more code
mixing_tab= "I \twas \t\tgiven \t\t\tdifferent \t\t\ttab" print(mixing_tab)
I was given different tab
there are more special character which we are going to discuss later but practice this for now and enjoy!