Python:退出for循环?

2024-06-11 03:04:19 发布

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

我做了一些调查,并意识到有许多类似的问题被问到,但我不能完全得到我的答案。不管怎样,我正在尝试构建一个库,用“塞萨尔数”技术“加密”一个字符串,这意味着我必须将字符串替换为字母表中另一个X位置以外的字母(我希望这是有意义的)。我的代码是:

from string import ascii_lowercase, ascii_uppercase

def creer_encodeur_cesar(distance):

    retour = lambda x: encodeur_cesar(x, distance)
    return retour

def encodeur_cesar(string, distance):
    tabLowerCase = list(ascii_lowercase)
    tabUpperCase = list(ascii_uppercase)
    tabString = list(string)

    l_encodedStr = []

    for char in tabString:
        position = 0
        if char == " ":
            pass
        elif char.isupper():
            #do something

        elif char.islower():
            for ctl in range(0, len(tabLowerCase)):
                position = ctl
                if char == tabLowerCase[ctl]:
                    if (ctl + distance) > 26:
                        position = ctl + distance - 25
                    char = tabLowerCase[position + distance]
                    l_encodedStr.append(char)
                    #How to break out of here??


        encodedStr = str(l_encodedStr)

        return encodedStr

encodeur5 = creer_encodeur_cesar(5)
print(encodeur5("lionel"))

所以,在我的第二个elif语句中,我想在成功地找到并加密了一个字符后中断,而不是在整个字母表中循环。我试图使用break,但它超出了主for循环。不是我想要的。我知道我可以使用tryexcept和{},但我不太知道如何才能做到这一点,这是个好主意吗?在

最好的办法是什么?在这种情况下有什么好的做法?在

如有任何帮助,请提前感谢!在


Tags: 字符串forstringifasciipositionlistdistance
1条回答
网友
1楼 · 发布于 2024-06-11 03:04:19

您可以使用^{}关键字。在

从文件中:

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print "Found an even number", num
...         continue
...     print "Found a number", num
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

相关问题 更多 >