Search code examples
pythonencryptionascii

using function to encrypt/decrypt a string


I'm tryna figure out how to encrypt/decrypt a string using a single function that takes a string and an offset as parameters. depending on the offset, the function encrypts or decrypts and builds new encrypt/decrypt string

Thanks a lot!

yeah so this is what the task is asking. I'm doing it atm

enter image description here


Solution

  • It seems like what you want is a caesar cipher which is relatively simple to do in python.

    def encrypt(text, key):
        """Encrypts text using a ceaser cypher"""
        encrypted = ""
        for char in text:
            if char.isalpha():
                encrypted += chr((ord(char) + key - 97) % 26 + 97)
            else:
                encrypted += char
        return encrypted
    

    The only really weird part about this code is the unicode character madness. If you don't know unicode/ascii is a way to map numbers in a computers memory to characters which computer memory is fundamentally just 1's and 0's. here's a chart for all the relevant character

    https://www.asc.ohio-state.edu/demarneffe.1/LING5050/material/ASCII-Table.png