How can I shorten this substitution cipher code?

Pytm :

The input string will consist of only alphabetic characters. The function should return a string where all characters have been moved "up" two spots in the alphabet.

For example:

  • "a" will become "c"
  • "z" will become "b"

I wrote this code, but I think it's too long. How can I make it shorter and better?

def encrypt_message(strings: str) -> str:
    our_al = ["a", "b", "c", "d", "e", "f", "g", "h", "i", 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
              'v', 'w', 'x', 'y', 'z']
    new_s = ""
    for character in strings:
        index = our_al.index(character)
        if index <= 23:
            index += 2
            new_s += our_al[index]
        elif index == 24:
            new_s += our_al[0]
        elif index == 25:
            new_s += our_al[1]

    return new_s


print(encrypt_message("abc"))
print(encrypt_message("xyz"))
print(encrypt_message(""))
schwobaseggl :

Some utils will be beneficial. If you use this function repeatedly you don't always want to iterate the chars to find the index, hence the lookup dict.

from string import ascii_lowercase as al

index = {c: i for i, c in enumerate(al)}

def encrypt_message(s: str) -> str:
    return ''.join(al[(index[c] + 2) % 26] for c in s)

>>> encrypt_message('xyz')
'zab'

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360734&siteId=1