-2

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.

2 Answers2

4

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"
gmds
  • 19,325
  • 4
  • 32
  • 58
  • Great it works, will accept when available. However, my actual use case is a string converted from a list with `s = r' '.join(s)`. Converting to a raw string does not solve this problem. – frantic oreo Jun 10 '19 at 06:52
  • 1
    @franticoreo How do you know that your string in fact has two backslashes? Note that each backslash will be printed twice. Try removing `{2,}` from the regex or just using `.replace('\\', '')`. – gmds Jun 10 '19 at 06:53
  • 1
    @franticoreo Note also that `r''.join(...)` is the same as `''.join(...)`. "raw string" only has meaning as a *literal*. – gmds Jun 10 '19 at 06:59
0

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'
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61