Remove all hex characters from string in Python

后端 未结 4 1176
失恋的感觉
失恋的感觉 2021-02-04 11:18

Although there are similar questions, I can\'t seem to find a working solution for my case:

I\'m encountering some annoying hex chars in strings, e.g.

\'         


        
4条回答
  •  天命终不由人
    2021-02-04 11:45

    Just remove all non-ASCII characters:

    >>> s.decode('utf8').encode('ascii', errors='ignore')
    'http://www.google.com blah blah#%#@$^blah'
    

    Other possible solution:

    >>> import string
    >>> s = '\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'
    >>> printable = set(string.printable)
    >>> filter(lambda x: x in printable, s)
    'http://www.google.com blah blah#%#@$^blah'
    

    Or use Regular expressions:

    >>> import re
    >>> re.sub(r'[^\x00-\x7f]',r'', s) 
    'http://www.google.com blah blah#%#@$^blah'
    

    Pick your favorite one.

提交回复
热议问题