Backslashes Are Complicated

Let's find out how backlashes are complicated in Python.

Overview of backlashes

Backslashes are a bit complicated in Python’s regular expressions. The reason is that regular expressions use backslashes to indicate special forms or to allow a special character to be searched for instead of invoking it, such as when we want to search for a dollar sign: $. If we don’t use backslash with dollar sign, we’d just be creating an anchor. The issue comes in because Python uses the backslash character for the same thing in literal strings. Let’s say we want to search for a string like this (minus the quotes): “python”.

Simple examples

To search for this in a regular expression, we will need to escape the backslash but because Python also uses the backslash, then that backslash also has to be escaped so we’ll end up with the following search pattern: “\\python”.

Get hands-on with 1200+ tech skills courses.