获取值时出错,不明白原因

2024-04-16 05:40:22 发布

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

我不太明白为什么下面的python代码会出现值错误。我知道(大部分情况下)它告诉我,无论我传递什么,它都找不到价值,但我真的不明白为什么

from string import ascii_lowercase
from math import gcd

lower = ascii_lowercase

def affineDecrypt(ciphertext, a, b):

    if gcd(a, 26) != 1:
        raise ValueError('a and 26 are not coprime. Please try again.')

    msg = ''.join(x for x in ciphertext if x.isalnum())
    out = ''
    n = 1
    count = 1

    while True:
        if a*n > 26*count:
            if a*n == (26*count) + 1:
                break
            count += 1
        n += 1

    for char in msg:
        if char.isalpha():
            d = int((n*(lower.index(char) - b)) % 26)
            out += lower[d]

        else:
            out += char

    return out
Error:
ValueError                                Traceback (most recent call last)
<ipython-input-32-8c8ae6f51f75> in <module>
----> 1 affineDecrypt('UBBAHK CAPJKX',17,20)

<ipython-input-31-215f26339a67> in affineDecrypt(ciphertext, a, b)
     23     for char in msg:
     24         if char.isalpha():
---> 25             d = int((n*(lower.index(char) - b)) % 26)
     26             out += lower[d]
     27 

ValueError: substring not found

救命啊


Tags: infromimportforifcountasciimsg
1条回答
网友
1楼 · 发布于 2024-04-16 05:40:22

您正在lower变量中查找大写“U”的索引,它是一个全小写字符串

强制char为小写:

d = int((n*(lower.index(char.lower()) - b)) % 26)

你应该没事的

另外,将lower变量名更改为其他名称。有一个字符串方法同名

相关问题 更多 >