tchadwik tchadwik - 1 year ago 189
Python Question

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?

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download