Raw Strings in Python
Raw Strings in Python’s re Module
Raw strings (prefixed with r) are highly recommended when working with regular expressions because they treat backslashes (\) as literal characters, preventing Python from interpreting them as escape sequences.
path = ‘C:\Users\Documents’
pattern = r’C:\Users\Documents’
.4.1.1. Escape sequences
Unless an 'r' or 'R' prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:
| Escape Sequence | Meaning | Notes |
|---|---|---|
\<newline> | Backslash and newline ignored | (1) |
\\ | Backslash (\) | |
\' | Single quote (') | |
\" | Double quote (") | |
\a | ASCII Bell (BEL) | |
\b | ASCII Backspace (BS) | |
\f | ASCII Formfeed (FF) | |
\n | ASCII Linefeed (LF) | |
\r | ASCII Carriage Return (CR) | |
\t | ASCII Horizontal Tab (TAB) | |
\v | ASCII Vertical Tab (VT) | |
\ooo | Character with octal value ooo | (2,4) |
\xhh | Character with hex value hh | (3,4) |
Escape sequences only recognized in string literals are:
| Escape Sequence | Meaning | Notes |
|---|---|---|
\N{name} | Character named name in the Unicode database | (5) |
\uxxxx | Character with 16-bit hex value xxxx | (6) |
\Uxxxxxxxx | Character with 32-bit hex value xxxxxxxx | (7) |