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.
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.
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.
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!
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.
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!']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With