Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python无法更正长度_Python_Python 2.7 - Fatal编程技术网

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

在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(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