从Python中的字符串中删除所有十六进制字符 [英] Remove all hex characters from string in Python
本文介绍了从Python中的字符串中删除所有十六进制字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尽管有类似的问题,但我似乎无法找到适合我的情况的解决方案:
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.
'\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'
我需要删除这些十六进制 \ xHH
字符,并单独删除它们,以获得以下结果:
What I need is to remove these hex \xHH
characters, and them alone, in order to get the following result:
'http://www.google.com blah blah#%#@$^blah'
解码无济于事:
s.decode('utf8') # u'\u201chttp://www.google.com\u201d blah blah#%#@$^blah'
我该如何实现?
推荐答案
只需删除所有非ASCII字符:
Just remove all non-ASCII characters:
>>> s.decode('utf8').encode('ascii', errors='ignore')
'http://www.google.com blah blah#%#@$^blah'
其他可能的解决方案:
>>> 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'
或使用正则表达式:
>>> import re
>>> re.sub(r'[^\x00-\x7f]',r'', s)
'http://www.google.com blah blah#%#@$^blah'
选择您最喜欢的一个.
这篇关于从Python中的字符串中删除所有十六进制字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文