Replace all non-alphanumeric characters in a string

前端 未结 4 581
谎友^
谎友^ 2020-12-23 02:39

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

4条回答
  •  心在旅途
    2020-12-23 03:09

    Regex to the rescue!

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

    Example:

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

提交回复
热议问题