Replace Non Alphanumeric Characters in Python
Posted September 22, 2022 by Rohith ‐ 1 min read
Non-alphanumeric characters in python string can be replaced using python regex module `re`
sub
method in re
module can be used to replace the non-alphanumeric characters.
Regular expression to exclude the alphanumeric string to be substituted is '[^0-9a-zA-Z]+'
.
It can be better explained with an example.
Example
Let’s say, we want to replace non-alphanumeric characters in the string wh!leTru-.l!v-
.
import re
host = 'wh!leTru-.l!v-'
non_alphanumeric_host = re.sub('[^0-9a-zA-Z]+', '_', host)
print(non_alphanumeric_host) # 'wh_leTru_l_v_'