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?
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'
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.
"h^&i => "h**i
"h*i"
Use \W which is equivalent to [^a-zA-Z0-9_] . Check out the documentation, https://docs.python.org/2/library/re.html.
\W
[^a-zA-Z0-9_]
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.
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
if(passCode[1]== ' '){ passCode[1]='_'; }; if(passCode[0]== ' '){ passCode[0]='_'; };