Strings | Escaping

The character \ , and one or more characters following it in the string literal, are replaced with a single character in the resulting string object, which has the binary value specified by the escape sequence.

Example:

>>> s = 'a\nb\tc'
>>> s
'a\nb\tc'
>>> print(s)
a
b	c

The \n represents a new line.
The \t represents a tab.

Find out how many characters there are in the string.

>>> len(s)
5

In the next example if you try to pen the path you will get an error since \n is considered a new line and \t
is considered a tab.

>>> path = 'C:\newfolder\text.dat'
>>> path
'C:\newfolder\text.dat'
>>> print(path)
C:
ewfolder	ext.dat
>>> path = r'C:\newfolder\text.dat'
>>> path
'C:\\newfolder\\text.dat'
>>> print(path)
C:\newfolder\text.dat

As you can see in the second part of the example, when using r which stands for regular expression, Python turns off the
escape mechanism. Alternatively, you could use double backslashes.

>>> path = 'C:\\newfolder\\text.dat'
>>> path
'C:\\newfolder\\text.dat'
>>> print(path)
C:\newfolder\text.dat

One backslash escapes the other one!

Leave a Reply