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?

5
  • 1
    Can you not just do res.replace ("\\", "").replace ("/", "") Commented Feb 15, 2018 at 12:15
  • 1
    The resulting regex is [!"#$%&'()*+,-./:;<=>?@[\]^_{|}~]` and the \ escaspes a ] in it. You should escape the symbols to match literal chars. Or at least escape the -, ], ^ and \. Commented Feb 15, 2018 at 12:18
  • 2
    Replace works just fine. Don't bother with regular expressions. Commented Feb 15, 2018 at 12:19
  • @Mathieu i think we should encourage the use of regex, as they are fast and efficient Commented Feb 15, 2018 at 12:20
  • also related escaping regex string in python : '[' + re.escape(symbolsToRemove) + ']' Commented Feb 15, 2018 at 12:24

2 Answers 2

2
import string import re symbolsToRemove = string.punctuation res = 'qwer!@ 234234 4234gdf36/\////// // \ \\\$%^$% dsfg' res = re.sub(r'[\\]*[\/]*','', res) print(res) 
Sign up to request clarification or add additional context in comments.

Comments

1

This should work with re.escape:

>>> print re.sub(r'['+re.escape(symbolsToRemove)+']+', ' ', res) qwer 234234 4234gdf36 dsfg 

4 Comments

Yes, it does: >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~'`
Sorry for the goof up. Yes OP just needs to do re.esacpe
I didn't get it - you previous answer did it well :) What's the matter to change it?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.