1

I'm making a Caesar cypher project in Python for my school assignment, I've done the base but I'm confused on how to move one letter forward. Recommend any methods?

def encrypt(word):
    # Somehow move one letter forward.

secret_word = encrypt(input("Enter word: "))
print(secret_word)
Filburt
  • 17,626
  • 12
  • 64
  • 115
LazyBeast
  • 45
  • 4

1 Answers1

2

You can use something in Python called ord to get the integer value and add that by one. Here is the solution:

def encrypt(word):
    encrypted = ""
    for letter in word:
        encrypted += chr(ord(letter) + 1)

    return encrypted

And if you want to the inverse of ord, then you can use chr. This would be the decrypt function:

def decrypt(word):
    decrypted = ""
    for letter in word:
        decrypted += chr(ord(letter) - 1)

    return decrypted

FYI, when a letter like "a" is used inside the ord function, it returns 97, and if we were to use the decrypt method on "a", then it would return " ` " which is not useful, but you can add a simple if statement which fixes this issue.

Glatinis
  • 337
  • 1
  • 13
  • And it should be noted `chr()` is the inverse of `ord()`; it takes a codepoint, as returned by `ord()`, and turns it into a string. – AKX Nov 25 '20 at 12:26