python中的索引错误
我是编程新手,我正在尝试使用python编写Vigenère加密密码。想法很简单,我的功能也很简单,但在这一行:python中的索引错误,python,encryption,Python,Encryption,我是编程新手,我正在尝试使用python编写Vigenère加密密码。想法很简单,我的功能也很简单,但在这一行: ( if((BinKey[i] == 'b')or(BinKey[i+1] == 'b')): ) 似乎我有一个索引问题,我不知道如何解决它。 错误消息是: IndexError: string index out of range 我试图用另一个等于I+1的变量替换I+1索引,因为我认为python可能在重新增加I,但它仍然不起作用 因此,我的问题是: 如何解决问题,我做错了
( if((BinKey[i] == 'b')or(BinKey[i+1] == 'b')): )
似乎我有一个索引问题,我不知道如何解决它。
错误消息是:
IndexError: string index out of range
我试图用另一个等于I+1
的变量替换I+1
索引,因为我认为python可能在重新增加I
,但它仍然不起作用
因此,我的问题是:
Bin\u It
功能:
def Bin_It(String):
TheBin = ""
for Charactere in String:
TheBin = TheBin + bin(ord(Charactere))
return TheBin
def Xor(a,b):
xor = (int(a) and not int(b)) or (not int(a) and int(b))
if xor:
return chr(1)
else:
return chr(0)
最后是Xor
函数:
def Bin_It(String):
TheBin = ""
for Charactere in String:
TheBin = TheBin + bin(ord(Charactere))
return TheBin
def Xor(a,b):
xor = (int(a) and not int(b)) or (not int(a) and int(b))
if xor:
return chr(1)
else:
return chr(0)
在您的while状态下,您将确保
i
。这意味着BinKey[i]
将是有效的,但是BinKey[i+1]
在循环的最后一次迭代中将无效,因为您将访问BinKey[len(BinKey)]
,它是字符串末尾的一个。python中的字符串从0
开始,在len-1
结束(包括len-1)
为了避免这种情况,可以将循环条件更新为
while BinKeyLength > i+1 and ...:
你可以改变
while ((BinKeyLengh > i) and (BinStringLengh > j)):
到
或改变
if((BinKey[i] == 'b')or(BinKey[i+1] == 'b')):
到
这将避免尝试进入超出范围的BinKey[BinKeyLength]
。正如Python解释器所说,我认为您的错误是访问了无效的数组位置。
为了解决这个问题,不像上面所说的,您应该将代码更改为
while(BinKeyLength>i+2和…):
这是因为在最后一步中,BinKeyLength=i+2,那么i+1就是BinKeyLength-1,它是数组的最后一个位置
关于您的编程技能,我向您推荐两件事:
- 这就是密码。听起来很神秘,但这里缺少的最重要的事情是弄清楚使用了哪些索引数字
- 正如rubik所说,遵循一些风格指南,如
看看我的代码,我能学到什么来提高我的编程技能
在索引上循环不是惯用的Python。最好尽可能在迭代器的元素上循环。毕竟,这通常是你感兴趣的:因为我在…
后面经常跟着我的列表[i]
在本例中,您应该使用内置函数(或者如果您的代码是惰性的,尽管在Python3中是惰性的),该函数为您提供来自两个或多个迭代器的成对值,并在最短迭代器耗尽时停止
for key_char, string_char in zip(BinKey, BinString): # takes values sequentially from
# BinKey and BinString
# and binds them to the names
# key_char and string_char
# do processing on key_char and string_char
如果您确实必须在索引上执行循环,那么将测试放在另一个方向,以便更清楚地了解您在做什么。比较
while len(BinKey) > i and len(BinString) > j: # this looks like len(BinKey) and
# len(BinString) are varying and you're
# comparing them to static variables i and j
与
似乎什么都没做。如果i==BinKeyLength
那么while
循环将立即停止。这几乎是不可读的Python代码。我建议您遵循PEP8风格指南!我同意。特别是,普通变量的多余括号和大首字母令人困惑。你到底想用Bin_It
实现什么?@Eric Bin_It返回一个包含字符串二进制值的字符串。希望它有意义。示例:Bin_It('aaa')返回:“0b11000010b11000010b1100001”@hamza:您意识到python有一个按位异或运算符,对吗ord(键[i])^ord(字符串[j])
执行您想要的操作,用于i
和j
while len(BinKey) > i and len(BinString) > j: # this looks like len(BinKey) and
# len(BinString) are varying and you're
# comparing them to static variables i and j
while i < len(BinKey) and j < len(BinString): # this looks like you're varying i and j
# and comparing them to len(BinKey) and len(BinString)
if (i == BinKeyLengh):
i = i+j