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.


>>> s = 'a\nb\tc'
>>> s
>>> print(s)
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)

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
>>> print(path)
ewfolder	ext.dat
>>> path = r'C:\newfolder\text.dat'
>>> path
>>> print(path)

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
>>> print(path)

One backslash escapes the other one!

Leave a Reply