Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting PEP8 "invalid escape sequence" warning trying to escape parentheses in a regex

I am trying to escape a string such as this:

string = re.split(")(", other_string)

Because not escaping those parentheses gives me an error. But if I do this:

string = re.split("\)\(", other_string)

I get a warning from PEP8 that it's an invalid escape sequence. Is there a way to do this properly?

Putting 'r' in front of the string does not fix it.

like image 616
Jack Avante Avatar asked Apr 29 '20 08:04

Jack Avante


People also ask

How do you fix an invalid escape character in a string?

Resolving The Problem which generates the Invalid escape sequence error. To re-iterate, the backslash character can be used as an escape sequence for a regular expression in a recognition property or a verification point. The compilation error only occurs when creating a regular expression in the script text.

What is escape character in python regex?

Python supports Regex via module re . Python also uses backslash ( \ ) for escape sequences (i.e., you need to write \\ for \ , \\d for \d ), but it supports raw string in the form of r'...' , which ignore the interpretation of escape sequences - great for writing regex.

Do I need to escape in regex python?

So if you want to match the '^' symbol, you can use it as the non-first character in a character class (e.g., pattern [ab^c] ). Note: It doesn't harm to escape the dot regex or any other special symbol within the character class—Python will simply ignore it!

How do you escape a character in python?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.


1 Answers

You probably are looking for this which would mean your string would be written as string = r")(" which would be escaped. Though that is from 2008 and in python 2 which is being phased out. What the r does is make it a "raw string"

See: How to fix "<string> DeprecationWarning: invalid escape sequence" in Python? as well.

What you're dealing with is string literals which can be seen in the PEP 8 Style Guide

UPDATE For Edit in Question:

If you're trying to split on ")(" then here's a working example that doesn't throw PEP8 warnings:

import re

string = r"Hello my darling)(!"
print(string)
string = re.split(r'\)\(', string)
print(string)

Which outputs:

Hello )(world!
['Hello ', 'world!']

Or you can escape the backslash explicitly by using two backslashes:

import re

string = r"Hello )(world!"
print(string)
string = re.split('\\)\\(', string)
print(string)

Which outputs the same thing:

Hello )(world!
['Hello ', 'world!']
like image 154
Treatybreaker Avatar answered Nov 11 '22 19:11

Treatybreaker