【发布时间】:2015-01-30 22:16:59
【问题描述】:
我正在尝试使用二维网格密码来加密 Python 中的字符串,但我的嵌套循环导致超出范围错误。
这是我的代码:
def encrypt():
before = str(input("Type a string to encrypt: "))
columns = int(input("How many table columns would you like: "))
split = [before[i:i+columns] for i in range(0, len(before), columns)]
rows = len(split)
after = []
for i in range(0, columns):
for j in range(0,rows):
after.append(split[j][i])
print(after)
这是我收到的错误:
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
encrypt()
File "E:/Python/cipher.py", line 12, in encrypt
after.append(split[j][i])
IndexError: string index out of range
【问题讨论】:
-
range(n)与range(0, n)相同。 0 是隐含的 -
你试过交换索引吗?使用
i遍历列,使用j遍历每个子字符串。所以你应该使用它们。 -
你检查过你的数组,看看它的元素是否是你期望的长度?
-
@tdelaney 我有,他们是