Python无法更正长度
在Python脚本中,我有一个变量,Python无法更正长度,python,python-2.7,Python,Python 2.7,在Python脚本中,我有一个变量,key,由AES解密算法输出,该算法的值为key=f9hygcyb2h1s0+2urrshknqgpx693s 此变量的长度似乎为32个字符。但是,运行len(key)会返回48。为什么会这样 key len(key) = 48 type(key) = <type 'str'>, Unicode? False print (key) = None. str(key) = F9hygcyyB2h1S0+2urrsHknqqGPx693s repr(k
key
,由AES解密算法输出,该算法的值为key=f9hygcyb2h1s0+2urrshknqgpx693s
此变量的长度似乎为32个字符。但是,运行len(key)
会返回48
。为什么会这样
key
len(key) = 48
type(key) = <type 'str'>, Unicode? False
print (key) = None.
str(key) = F9hygcyyB2h1S0+2urrsHknqqGPx693s
repr(key) = 'F9hygcyyB2h1S0+2urrsHknqqGPx693s\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10'
key = key.encode('ascii', 'ignore')
Length: 48. Type: <type 'str'>, Unicode? False
key = unicode(key)
Length: 48. Type: <type 'unicode'>, Unicode? True
key = key.decode('utf-8')
Length: 48. Type: <type 'unicode'>, Unicode? True
这将消除所有不可打印的字符,在测试中,它被证明等于预期值。看起来在
键中有一些不可打印的字符。您可以轻松摆脱它们:
newkey = ''.join(x for x in key if x.isprintable()) # Python 3
newkey = ''.join(x for x in key if x in string.printable) # Python 2
len(newkey)
# 32
但这将是一把不同的钥匙 至少根据我的Python 3.4,你的键的长度是32。Python 2.7.6也给出了32。打印类型(键)
的输出是什么?打印repr(键)
打印什么?你能给我们看一下打印(键)
,str(键)
,和repr(键)
,以防万一?我得到的“str”对象没有属性“isprintable”
。已为Python 2更新。
newkey = ''.join(x for x in key if x.isprintable()) # Python 3
newkey = ''.join(x for x in key if x in string.printable) # Python 2
len(newkey)
# 32