|
|
阳刚的红茶 · Photos and Videos for ...· 6 月前 · |
|
|
气势凌人的核桃 · 上万张照片怎么找?百度网盘:你只管说,我们帮 ...· 6 月前 · |
|
|
不爱学习的甘蔗 · 榕树盆景的养殖方法和注意事项-百度经验· 7 月前 · |
|
|
千年单身的冲锋衣 · 国家医疗保障局政策法规国家医疗保障局关于完善 ...· 7 月前 · |
|
|
发怒的洋葱 · 征途手机版新手攻略老司机教你怎么玩征途_43 ...· 1 年前 · |
我需要用Python 3使用xor加密/解密一个文件,我有一个在Python 2中运行良好的代码,但是当试图将它修改到Python 3时,会给我一些我无法解决的错误。
这段代码在Python2.7中运行得很好:
from itertools import cycle
def xore(data, key):
return ''.join(chr(ord(a) ^ ord(b)) for (a, b) in zip(data, cycle(key)))
with open('inputfile.jpg', 'rb') as encry, open('outputfile.jpg', 'wb') as decry:
decry.write(xore(encry.read(), 'anykey'))
在python 3中尝试不更改地运行时出错:
Traceback (most recent call last):
File "ask.py", line 8, in <module>
decry.write(xore(encry.read(), 'anykey'))
File "ask.py", line 5, in xore
return ''.join(chr(ord(a) ^ ord(b)) for (a, b) in zip(data, cycle(key)))
File "ask.py", line 5, in <genexpr>
return ''.join(chr(ord(a) ^ ord(b)) for (a, b) in zip(data, cycle(key)))
TypeError: ord() expected string of length 1, but int found
如果有人能解释并帮助我将这段代码改编成Python 3,请允许我这样做。
发布于 2015-09-19 19:32:33
a
已经是一个
int
,所以您需要删除对
ord(a)
的调用。
def xore(data, key):
return ''.join(chr(a ^ ord(b)) for (a, b) in zip(data, cycle(key)))
如果没有
.encode("utf-8")
,您将无法将连接字符串写入到外部文件,这将不会为您提供任何可用的输出,因此无法确定您实际要实现的是什么。
您可以看到,当您索引字节字符串时,可以在python3中得到一个int:
n [1]: s = b"foo"
In [2]: s[0]
Out[2]: 102 # f
在python2中哪里可以得到str/char:
In [1]: s = b"foo"
In [2]: s[0]
Out[2]: 'f'
迭代或调用next还会给出整数值:
In [12]: it = iter(s)
In [13]: next(it)
Out[13]: 102
In [14]: for ele in s:
print(ele)
|
|
不爱学习的甘蔗 · 榕树盆景的养殖方法和注意事项-百度经验 7 月前 |