Replace all non-alphanumeric characters in a string

前端 未结 4 571
谎友^
谎友^ 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'
    
    0 讨论(0)
  • 2020-12-23 03:23

    Use \W which is equivalent to [^a-zA-Z0-9_]. Check the documentation, https://docs.python.org/2/library/re.html

    Import re
    s =  'h^&ell`.,|o w]{+orld'
    replaced_string = re.sub(r'\W+', '*', s)
    output: 'h*ell*o*w*orld'
    

    update: This solution will exclude underscore as well. If you want only alphabets and numbers to be excluded, then solution by nneonneo is more appropriate.

    0 讨论(0)
  • 2020-12-23 03:27

    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.

    0 讨论(0)
  • 2020-12-23 03:31

    Try:

    s = filter(str.isalnum, s)
    

    in Python3:

    s = ''.join(filter(str.isalnum, s))
    

    Edit: realized that the OP wants to replace non-chars with '*'. My answer does not fit

    0 讨论(0)
提交回复
热议问题