25

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.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Jack Avante
  • 1,405
  • 1
  • 15
  • 32

1 Answers1

26

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!']
Treatybreaker
  • 776
  • 5
  • 9
  • 1
    The raw string formatting r"str" doesn't seem to work to fix the issue in Python 3.8 but the double backslash works great, thanks! – Jack Avante Apr 29 '20 at 08:50