4

I have a string:

res = 'qwer!@ 234234 4234gdf36/\////// // \ \\\$%^$% dsfg'

and I want to remove ALL slashes and backslashes. I tried this:

import string
import re

symbolsToRemove = string.punctuation
res = 'qwer!@ 234234 4234gdf36/\////// // \ \\\$%^$% dsfg'
res = re.sub(r'['+symbolsToRemove+']', ' ', res)
print(res)

But get the next result:

qwer 234234 4234gdf36 \ \ \ dsfg

What am I doing wrong?

Mikhail_Sam
  • 10,602
  • 11
  • 66
  • 102

2 Answers2

2
import string
import re
symbolsToRemove = string.punctuation
res = 'qwer!@ 234234 4234gdf36/\////// // \ \\\$%^$% dsfg'
res = re.sub(r'[\\]*[\/]*','', res)
print(res)
user5722540
  • 590
  • 8
  • 24
1

This should work with re.escape:

>>> print re.sub(r'['+re.escape(symbolsToRemove)+']+', ' ', res)
qwer  234234 4234gdf36        dsfg
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Yes, it does: `>>> string.punctuation` `'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'` – Thierry Lathuille Feb 15 '18 at 12:22
  • Sorry for the goof up. Yes OP just needs to do `re.esacpe` – anubhava Feb 15 '18 at 12:26
  • I didn't get it - you previous answer did it well :) What's the matter to change it? – Mikhail_Sam Feb 15 '18 at 12:28
  • @Mikhail_Sam: Previous answer also worked because it had separate \\ but I had wrong explanation. This one will also work because `re.escape(symbolsToRemove)` will escape each and every special character in `symbolsToRemove` string where \ is already present. – anubhava Feb 15 '18 at 12:30