0

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

I've written a function that only works if the (index of a letter + 13) is in range.

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, e.g. rot13('Test'), of course I get the 'string index is out of range' error, how should i go about that problem?

3

1 Answer 1

1

Use the modulo operator %:

Modulo devides the number by the given factor and keeps the rest, eg:

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.