Hackerss.com

hackerss
hackerss

Posted on

Implement a decoder for the ceasar cipher in Python

Implement a decoder for the ceasar cipher - Python:


#create a function that takes in a string and an integer
def decode(string, shift):
    """
    Decode a string using the ceasar cipher.

    Parameters
    ----------
    string : str
        String to decode.
    shift : int
        Number of characters to shift.

    Returns
    -------
    str
        Decoded string.
    """

    #create an empty string to store the decoded string
    decoded_string = ""

    #loop through each character in the string
    for char in string:

        #if the character is a letter, shift it by the shift amount
        if char.isalpha():
            if char.isupper():
                decoded_string += chr((ord(char) - 65 - shift) % 26 + 65)
            else:
                decoded_string += chr((ord(char) - 97 - shift) % 26 + 97)

        #if the character is not a letter, add it to the decoded string without shifting it
        else:
            decoded_string += char

    #return the decoded string
    return decoded_string


#example
result = decode("I am a hacker", 2)
#output
print(result)  #"I am a hacker"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)