The Python Apprentice
上QQ阅读APP看书,第一时间看更新

Raw strings

Sometimes, particularly when dealing with strings such as Windows filesystem paths or regular expression patterns which use backslashes extensively, the requirement to double-up on backslashes can be ugly and error prone. Python comes to the rescue with its raw strings. Raw strings don't support any escape sequences and are very much what-you-see-is-what-you-get. To create a raw string, precede the opening quote with a lower-case r:

>>> path = r'C:\Users\Merlin\Documents\Spells'
>>>
>>> path
'C:\\Users\\Merlin\\Documents\\Spells'
>>> print(path)
C:\Users\Merlin\Documents\Spells
Although it's common to store and manipulate filesystem paths as strings, for anything but the most straightforward path handling, you should investigate the Python Standard Library pathlib module.