[英]how to decode utf-16 with % as delimiter string to the original form in python3?
我正在與移動運營商合作,該運營商通過某種utf-16編碼的字符串通知我。 例如, '%u062a%u0633%u062a'
等價於波斯語中的'تست'
。 我不確定這些字符串的確切編碼是什么。 我如何將它們轉換為像'تست'
這樣'تست'
真實形式?
一種簡單的方法是將%
替換為\\
以使其成為帶有轉義的unicode字符的python文字,然后使用unicode-escape
對其進行解碼。
s = b'%u062a%u0633%u062a'
print(s.replace(b'%', b'\\').decode('unicode-escape'))
您可以將字符十六進制值除以%u,然后使用內置函數chr
查找Unicode chr
。
def convert_to_unicode(text):
return_str = ''
for character in text.split('%u'):
if character:
chr_code = int(character, 16)
return_str += chr(chr_code)
return return_str
text = '%u062a%u0633%u062a'
print(convert_to_unicode(text))
輸出:
تست
或者,您可以通過blhsing在其他答案中使用unicode轉義。
def convert_to_unicode(text: str):
# Replace %.
text = text.replace('%', '\\')
# Escape unicode into character.
text = text.encode().decode('unicode-escape')
return text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.