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 SequenceMeaningNotes
\<newline>Backslash and newline ignored(1)
\\Backslash (\)
\'Single quote (')
\"Double quote (")
\aASCII Bell (BEL)
\bASCII Backspace (BS)
\fASCII Formfeed (FF)
\nASCII Linefeed (LF)
\rASCII Carriage Return (CR)
\tASCII Horizontal Tab (TAB)
\vASCII Vertical Tab (VT)
\oooCharacter with octal value ooo(2,4)
\xhhCharacter with hex value hh(3,4)

Escape sequences only recognized in string literals are:

Escape SequenceMeaningNotes
\N{name}Character named name in the Unicode database(5)
\uxxxxCharacter with 16-bit hex value xxxx(6)
\UxxxxxxxxCharacter with 32-bit hex value xxxxxxxx(7)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *