Reassigning letters in an alphet to a higher letter in python?

后端 未结 2 1527
被撕碎了的回忆
被撕碎了的回忆 2021-01-29 09:30

If I am building a basic encryption program in python that reassigns A to C and D to F and so on, what is a simple algorithm I could use to do this? I have a list named alphabet

相关标签:
2条回答
  • 2021-01-29 10:08

    str.translate should be the easiest way:

    table = str.maketrans(
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
        "cdefghijklmnopqrstuvwxyzabCDEFGHIJKLMNOPQRSTUVWXYZAB"
    )
    s = "Test String"
    print(s.translate(table))
    

    Output:

    Vguv Uvtkpi
    
    0 讨论(0)
  • 2021-01-29 10:15

    There's two major parts to this. First, ciphering a single letter; and second, applying that to the whole string. We'll start with the first one.

    You said you had a list with the alphabet in it. Suppose, too, that we have a letter.

    >>> letter = 'F'
    

    If we want to replace that letter with the letter two spaces down in the alphabet, first we'll probably want to find the numerical value of that letter. To do that, use index:

    >>> alphabet.index(letter)
    5
    

    Next, you can add the offset to it and access it in the list again:

    >>> alphabet[alphabet.index(letter) + 2]
    'H'
    

    But wait, this won't work if we try doing a letter like Z, because when we add the index, we'll go off the end of the list and get an error. So we'll wrap the value around before getting the new letter:

    >>> alphabet[(alphabet.index('Z') + 2) % len(alphabet)]
    'B'
    

    So now we know how to change a single letter. Python makes it easy to apply it to the whole string. First putting our single-letter version into a function:

    >>> def cipher_letter(letter):
    ...     return alphabet[(alphabet.index(letter) + 2) % len(alphabet)]
    ...
    

    We can use map to apply it over a sequence. Then we get an iterable of ciphered characters, which we can join back into a string.

    >>> ''.join(map(cipher_letter, 'HELLOWORLD'))
    'JGNNQYQTNF'
    

    If you want to leave characters not in alphabet in place, add a test in cipher_letter to make sure that letter in alphabet first, and if not, just return letter. Voilà.

    0 讨论(0)
提交回复
热议问题