How to remove characters from a string using Python?

I start with both Python and RegEx, and I would like to know how to make a string that accepts characters and replaces them with spaces. Any help is great.

For example:

how much for the maple syrup? $20.99? That ricidulous!!! 

at

 how much for the maple syrup 20 99 That s ridiculous 
+54
python string regex
May 18 '09 at 1:55
source share
3 answers

In one case, using regular expressions :

 >>> s = "how much for the maple syrup? $20.99? That ridiculous!!!" >>> re.sub(r'[^\w]', ' ', s) 'how much for the maple syrup 20 99 That s ridiculous ' 
  • \w will match alphanumeric and underscore characters

  • [^\w] will match any that is not alphanumeric or underscore

+111
May 18 '09 at 1:59 a.m.
source share

Sometimes it takes more time to figure out a regular expression than just writing it in python:

 import string s = "how much for the maple syrup? $20.99? That ricidulous!!!" for char in string.punctuation: s = s.replace(char, ' ') 

If you need other characters, you can change it to use the whitelist or expand your blacklist.

Sample whitelist:

 whitelist = string.letters + string.digits + ' ' new_s = '' for char in s: if char in whitelist: new_s += char else: new_s += ' ' 

An example of a whitelist using a generator expression:

 whitelist = string.letters + string.digits + ' ' new_s = ''.join(c for c in s if c in whitelist) 
+21
May 18 '09 at 9:24
source share

I often open the console and look for a solution in object methods. Quite often this is already there:

 >>> a = "hello ' s" >>> dir(a) [ (....) 'partition', 'replace' (....)] >>> a.replace("'", " ") 'hello s' 

Short answer: use string.replace() .

+4
May 18 '09 at 5:45 a.m.
source share



All Articles