Replace all non-letter characters in a string

I have a line in which I want to replace any character that is not a standard character or number, for example (az or 0-9) with an asterisk. For example, "h ^ & ell`., | O w] {+ orld" is replaced by "h * ell * o * w * orld". Please note that replace several characters such as "^ &" with one asterisk. How can i do this?

+79
python
Oct 20 '12 at 5:10
source share
5 answers

Regex to the rescue!

import re s = re.sub('[^0-9a-zA-Z]+', '*', s) 

Example:

 >>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|ow]{+orld') 'h*ell*o*w*orld' 
+143
Oct 20 '12 at 5:11
source share

The pythonic way.

 print "".join([ c if c.isalnum() else "*" for c in s ]) 

This does not apply to the grouping of several consecutive mismatched characters, i.e.

"h^&i => "h**i not "h*i" as in regular expression solutions.

+32
Feb 28 '14 at 13:27
source share

Use \W which is equivalent to [^a-zA-Z0-9_] . Check out the documentation, https://docs.python.org/2/library/re.html.

 Import re s = 'h^&ell'.,|ow]{+orld' replaced_string = re.sub(r'\W+', '*', s) output: 'h*ell*o*w*orld' 

update: this solution will also exclude underlining. If you want only alphabets and numbers to be excluded, then a solution from nneonneo is more suitable.

+10
Aug 12 '16 at 18:54
source share

Try:

 s = filter(str.isalnum, s) 

in Python3:

 s = ''.join(filter(str.isalnum, s)) 

Change: realized that the OP wants to replace non-characters with '*'. My answer does not fit

+7
Jan 05 '15 at 5:15
source share
 if(passCode[1]== ' '){ passCode[1]='_'; }; if(passCode[0]== ' '){ passCode[0]='_'; }; 
0
Feb 07 '19 at 0:27
source share



All Articles