加密程序, 字符串索引超出范围

2024-04-25 21:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个初学者程序员,我遇到了一个我不能解决的问题。我正在创建一个程序,通过依次将每个字母的序数值与文本中每个字母的序数值相加来加密文本,并使用chr()函数打印新字符。你知道吗

codeword = input('Enter codeword : ')
encrypt = input('Enter text to encrypt : ')
j = 0
for i in encrypt:
    check = (ord(encrypt[j])+ ord(codeword[j])-96)
    if check > 122:
        no = check - 26
        ok = (chr(no))
        ok = ok.replace("%", " ")
        print(ok, end="")
    if check < 122:
        yes = (chr(check))
        yes = yes.replace("%", " ")
        print(yes, end="")
    j+=1

当我选择abc作为码字,hey作为要加密的字时,它可以很好地工作并打印igb。但是,如果我选择abc作为密码,选择helloworld作为要加密的单词,我将收到以下消息。你知道吗

Traceback (most recent call last):
  File "C:/Python34/task 2.py", line 9, in <module>
    check = (ord(encrypt[j])+ ord(codeword[j])-96)
IndexError: string index out of range

Tags: noin文本inputifcheck字母ok
1条回答
网友
1楼 · 发布于 2024-04-25 21:00:44

因为encryptcodeword长,所以可以到达,比如说,索引5encrypt[5], but codeword[5]不存在。你需要找到最短的:

for e, c in zip(encrypt, codeword):
    check = (ord(e) + ord(c) - 96)
    ...

您还可以使用min()函数:

for j in range(min(len(encrypt), len(codeword))):
    ...

编辑:似乎您希望循环。您可以使用itertools执行该任务:

from itertools import cycle

for e, c in zip(encrypt, cycle(codeword)):
    ...

cycle()将永远遍历对象。当它到达终点时,它又回到起点。例如:

for char in cycle("here"):
    print(char)

h
e
r
e
h
e
r
e
h
...

因为zip()只能循环到最短的iterable,所以它只能循环到encrypt的长度。例如:

for e, c in zip("this sentence", cycle("abc")):
    print(e, c)

t a
h b
i c
s a
  b
s c
e a
n b
t c
e a
n b
c c
e a

如果encryptcodeword短,它仍然有效:

for e, c in zip("hi", cycle("abc")):
    print(e, c)

h a
i b

编辑2:似乎要将空格保留为空格。你可以这样做:

for e, c in zip(encrypt, cycle(codeword)):
    if e == " ":
        check = ord(e)
    else:
        check = (ord(e) + ord(c) - 96)
    ...

相关问题 更多 >