Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove symbols from a string with Python? [duplicate]

I'm a beginner with both Python and RegEx, and I would like to know how to make a string that takes symbols and replaces them with spaces. Any help is great.

For example:

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

into:

how much for the maple syrup 20 99 That s ridiculous 
like image 784
aaront Avatar asked May 18 '09 01:05

aaront


People also ask

How do I remove symbols from text in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

How do you remove duplicate codes in Python?

You can remove duplicates from a Python using the dict. fromkeys(), which generates a dictionary that removes any duplicate values.


1 Answers

One way, using regular expressions:

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

  • [^\w] will match anything that's not alphanumeric or underscore

like image 159
dF. Avatar answered Sep 25 '22 14:09

dF.