简体   繁体   English

如何在加密字符串的函数中修复“字符串索引超出范围”错误

[英]How to fix 'string index out of range' error in a function that ciphers a string

I don't know how to efficiently go back to the beginning of the alphabet, when (index of a letter + 13) is out of range 我不知道如何有效地回到字母表的开头,当(字母索引+13)超出范围时

I've written a function that only works if the (index of a letter + 13) is in range. 我编写了一个仅在(字母索引+13)在范围内时才有效的函数。

def rot13(message):
    letters = [i for i in message]
    for i in letters:
        if i.isupper():
            letters[letters.index(i)] = 
string.ascii_uppercase[string.ascii_uppercase.index(i) + 13]
        elif i.islower():
            letters[letters.index(i)] = 
string.ascii_lowercase[string.ascii_lowercase.index(i) + 13]
        else:
            continue
    return ''.join(letters)

When I call, eg rot13('Test'), of course I get the 'string index is out of range' error, how should i go about that problem? 当我打电话时,例如rot13('Test'),当然我得到'字符串索引超出范围'错误,我应该怎么解决这个问题?

Use the modulo operator % : 使用模运算符%

Modulo devides the number by the given factor and keeps the rest, eg: Modulo将数字除以给定因子并保留其余因子,例如:

27 % 26 = 1

In your case it would be this two lines: 在你的情况下,这将是这两行:

string.ascii_uppercase[(string.ascii_uppercase.index(i) + 13) % 26]

string.ascii_lowercase[(string.ascii_uppercase.index(i) + 13) % 26]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM