Replace all non-alphanumeric characters in a string


I have a string with which i want to replace any character that isn't a standard character or number such as (a-z or 0-9) with an asterisk. For example, "h^&ell`.,|o w]{+orld" is replaced with "h*ell*o*w*orld". Note that multiple characters such as "^&" get replaced with one asterisk. How would I go about doing this?

This question is tagged with python

~ Asked on 2012-10-20 05:10:04

The Best Answer is


Regex to the rescue!

import re

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


>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')

~ Answered on 2012-10-20 05:11:02


The pythonic way.

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

This doesn't deal with grouping multiple consecutive non-matching characters though, i.e.

"h^&i => "h**i not "h*i" as in the regex solutions.

~ Answered on 2014-02-28 13:27:31

Most Viewed Questions: