首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Binascii.unhexlify类型错误奇数长度字符串

Binascii.unhexlify类型错误奇数长度字符串
EN

Stack Overflow用户
提问于 2015-10-13 10:02:43
回答 1查看 1.6K关注 0票数 0

我已经写了以下脚本来摆脱非字母数字字符,并在事后将它们取回。然而,我似乎不明白为什么unhexlify不能工作。有什么建议吗?

代码语言:javascript
复制
import binascii, timeit, re

damn_string = "asjke5234nlkfs$sfj3.$sfjk."

def convert_string(s):
    return ''.join('__UTF%s__' % binascii.hexlify(c.encode('utf-16')) if not c.isalnum() else c for c in s.lower())

def convert_back(s):
    for i in re.findall('__UTF([a-f0-9]{8})__', s): # For testing
        print binascii.unhexlify(i).decode('utf-16')
    return re.sub('__UTF([a-f0-9]{8})__', binascii.unhexlify('\g<1>').decode('utf-16'), s)

convert = convert_string(damn_string)
print convert
print convert_back(convert)

将产生以下输出:

代码语言:javascript
复制
asjke5234nlkfs__UTFfffe2400__sfj3__UTFfffe2e00____UTFfffe2400__sfjk__UTFfffe2e00__
$
.
$
.
Traceback (most recent call last):
  File "test.py", line 131, in <module>
    print convert_back(convert)
  File "test.py", line 127, in convert_back
    return re.sub('__UTF([a-f0-9]{8})__', binascii.unhexlify('\g<1>').decode('utf-16'), s)
TypeError: Odd-length string
EN

回答 1

Stack Overflow用户

发布于 2015-10-13 10:35:14

是我的错。我花了很长时间才意识到re.sub不能以这种方式提交组字符串。这样做的一种方法是:

代码语言:javascript
复制
return re.sub('__UTF([a-f0-9]{8})__', lambda x: binascii.unhexlify(x.group(1)).decode('utf-16'), s)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33092948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档