Regex will not sub characters '\'

Question:

I want to remove the characters \ from my string. I have tried regextester and it matches, https://regex101.com/r/euGZsQ/1

 s = '''That\'s not true. There are a range of causes. There are a        range of issues that we have to address. First of all, we have to identify, share and accept that there is a problem and that we\''''

 pattern = re.compile(r'\{2,}')
 re.sub(pattern, '', s)

I would expect the sub method to replace my \ with nothing to clean up my string.

Asked By: frantic oreo

||

Answers:

The problem is that your string itself is not marked as a raw string. Therefore, the first actually escapes the second.

Observe:

import re

pattern = re.compile(r'\{2,}')
s = r'''That\'s not true. There are a range of causes. There are a        range of issues that we have to address. First of all, we have to identify, share and accept that there is a problem and that we\'''
re.sub(pattern, '', s)

Output:

"That's not true. There are a range of causes. There are a        range of issues that we have to address. First of all, we have to identify, share and accept that there is a problem and that we"
Answered By: gmds

You can try:

import re
s = '''That\'s not true. There are a range of causes. There are a        range of issues that we have to address. First of all, we have to identify, share and accept that there is a problem and that we\' '''
d = re.sub(r'\', '', s)
print(d)

Output :

That's not true. There are a range of causes. There are a        range of issues that we have to address. First of all
, we have to identify, share and accept that there is a problem and that we'
Answered By: Harsha Biyani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.