liveBook · Manning

Raw string literal

As explained in Natural Language Processing in Action, Second Edition

A Python string literal in which backslashes are preserved rather than normally interpreted as escape sequences.

A raw string literal preserves backslashes instead of interpreting them as escape sequences. In regular expressions, prefixing a quoted string with r avoids doubling every backslash, keeping patterns such as \s and \{ readable. section 1.5.2

>>> r = r"[^a-z]*([y]o|[h']?ello|ok|hey|(good[ ])(morn[gin']{0,3}|"
>>> r += r"afternoon|even[gin']{0,3}))[\s,;:]{1,3}([a-z]{1,20})"
>>> re_greeting = re.compile(r, flags=re.IGNORECASE)    #1
>>> re_greeting.match('Hello Rosa')
<re.Match object; span=(0, 10), match='Hello Rosa'>
>>> re_greeting.match('Hello Rosa').groups()
('Hello', None, None, 'Rosa')
>>> re_greeting.match("Good morning Rosa")
<re.Match object; span=(0, 17), match="Good morning Rosa">
>>> re_greeting.match("Good Manning Rosa")                  #2
>>> re_greeting.match('Good evening Rosa Parks').groups()    #3
('Good evening', 'Good ', 'evening', 'Rosa')
>>> re_greeting.match("Good Morn'n Rosa")
<re.Match object; span=(0, 16), match="Good Morn'n Rosa">
>>> re_greeting.match("yo Rosa")
<re.Match object; span=(0, 7), match='yo Rosa'>

Shows a multi-line raw regular expression using character classes, whitespace matching, grouping, and compiled matching. section 1.5.2

How Natural Language Processing in Action, Second Edition covers it

How deep it goes
Defines backslash preservation and contrasts raw patterns with doubled escapes, without detailing string-parser internals.
Examples
Uses whitespace matching, literal curly braces, greeting patterns, and compiled regular expressions as examples.
What it assumes
Assumes basic Python strings and regular expressions while clarifying escape handling from the immediate examples.
What you can do after
Apply raw string literals to write more readable Python regular-expression patterns with unmodified backslashes.
How it connects
Connects raw string literals to regular expressions, escape sequences, character classes, and the re package.

Also explained in

Compare how 3 books explain raw string literal →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Natural Language Processing in Action, Second Edition. The section links point to the parts of the book it draws on.