Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in

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.

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

        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)
                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
            decoded_string += char

    #return the decoded string
    return decoded_string

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

Top comments (0)