Home > Blockchain >  When going out of bounds in a list, how can I go back to the start of the list in Python? [duplicate
When going out of bounds in a list, how can I go back to the start of the list in Python? [duplicate

Time:10-04

I'm making a Caeser cipher-type program. (To obfuscate and decode strings)

I decided to go with a system that has an iterable string with all the characters in the alphabet. I loop over every character in a string given to decode, and find its index in the alphabet. Once it is found, I get the character at an index 1 before the current character. The issue with my system is that if I have a string with an "A" in it, (or other characters if I increase the reverseamount variable), it goes out of range. How can I go to the opposite end of the array once this happens?

Here's part of my code right now.

alphabet = 'abcdefghijklmnopqrstuvwxyz'

def crack(string):
    cracked = False 
    amountToReverse = 1
    while not cracked:
        fullstring = '' # The resulting cracked string

        for char in string:
            if char in alphabet:
                index = alphabet.find(char)

                reversedChar = alphabet[index - amountToReverse]

                fullstring = fullstring   reversedChar # adds the decoded character to the resulting string.

Sorry if my question is poorly formatted, this is my first time!

CodePudding user response:

Use the modulo operator (%) to get the remainder of dividing the result of the subtraction by the length of alphabet:

reversedChar = alphabet[(index - amountToReverse) % len(alphabet)]
  • Related