簡體   English   中英

Python UTF-8轉換

[英]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')
事業

謝謝。

你可以使用intunichr來轉換它們:

>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM