[英]Python UTF-8 conversion
我想問一下Python程序如何進行以下轉換(source-> target)。
>>> source = '\\x{4e8b}\\x{696d}'
>>> print source
\x{4e8b}\x{696d}
>>> print type(source)
<type 'str'>
>>> target = u'\u4e8b\u696d'
>>> print target.encode('utf-8')
事業
謝謝。
你可以使用int
和unichr
來轉換它們:
>>> int('4e8b', 16)
20107
>>> unichr(int('4e8b', 16))
u'\u4e8b'
>>> print unichr(int('4e8b', 16))
事
利用Blender的想法,你可以使用帶有可調用替換參數的re.sub :
import re
def touni(match):
return unichr(int(match.group(1), 16))
source = '\\x{4e8b}\\x{696d}'
print(re.sub(r'\\x\{([\da-f]+)\}', touni, source))
產量
事業
import re
p = re.compile(r'[\W\\x]+')
print ''.join([unichr(int(y, 16)) for y in p.split(source) if y != ''])
事業
也從@Blender偷走了想法......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.