[英]Remove all hex characters from string in Python
雖然有類似的問題,但我似乎無法為我的案例找到一個有效的解決方案:
我在字符串中遇到一些討厭的十六進制字符,例如
'\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'
我需要的是刪除這些hex \\xHH
字符,並單獨刪除它們,以獲得以下結果:
'http://www.google.com blah blah#%#@$^blah'
解碼沒有幫助:
s.decode('utf8') # u'\u201chttp://www.google.com\u201d blah blah#%#@$^blah'
我怎樣才能做到這一點?
只需刪除所有非ASCII字符:
>>> 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'
選擇你最喜歡的一個。
這些不是“十六進制字符”,而是內部表示(在第一種情況下編碼為utf-8,在第二種情況下為unicode代碼點)的unicode字符“LEFT DOUBLE QUOTATION MARK”(“”“)和”右雙引號“ '(''')。
>>> s = "\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah"
>>> print s
“http://www.google.com” blah blah#%#@$^blah
>>> s.decode("utf-8")
u'\u201chttp://www.google.com\u201d blah blah#%#@$^blah'
>>> print s.decode("utf-8")
“http://www.google.com” blah blah#%#@$^blah
至於如何刪除它們,它們只是普通的字符,所以一個簡單的str.replace()
將會:
>>> s.replace("\xe2\x80\x9c", "").replace("\xe2\x80\x9d", "")
'http://www.google.com blah blah#%#@$^blah'
如果你想一次性刪除所有非ascii字符,你只需要解碼為unicode然后使用“ignore”參數編碼為ascii:
>>> s.decode("utf-8").encode("ascii", "ignore")
'http://www.google.com blah blah#%#@$^blah'
您可以檢查有效字母,而不是鍵入所有內容,可以使用string
模塊。 可能對您有用的是string.ascii_letters
(包含string.ascii_lowercase
和string.ascii_uppercase
), string.digits
, string.printable
和string.punctuation
。
我首先嘗試使用string.printable
,但如果它允許一些太多的字符通過,你可以使用其他的混合。
這是我如何做的一個例子:
import string
valid_characters = string.printable
start_string = '\xe2\x80\x9chttp://www.google.com\xe2\x80\x9d blah blah#%#@$^blah'
end_string = ''.join(i for i in start_string if i in valid_characters)
您可以像這樣在編碼后使用解碼
s.encode('ascii', errors='ignore').decode("utf-8")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.