5.6) Special Characters
A string can be made of any characters, but some characters can have special meanings for Python. To control this behaviour, we use a backslash ('\') to change the meaning of the following character in a string.
Here is a list of some important backslash-sequences in Python:
Sequence | Meaning |
\\ | Backslash (\) |
\' | Single Quotation Mark (') |
\" | Double Quotation Mark (") |
\n | Start a new line |
\t | Horizontal Tab |
For example:
>>> print "This string\nhas two lines" >>> print "c:\\users\\tom"
If you forgot to double the backslashes, '\t' would be printed as a tab.
If you have lots of special characters in a string, for example lots of backslashes in the location of a file on a computer (c:\users\tom), you can create a 'raw' string. This is simply preceded by the letter r, and all characters have their regular meaning:
>>> print r"c:\users\tom"
This time the backslash characters are treated as ordinary backslashes, and you can't include special characters like tabs, new lines or double quotation marks.
Write a program that uses all of these special characters and a raw string. See what happens if you mix double and single quotation marks in a string.