简体   繁体   中英

Ascii strings in Python

I'm currently working on setting up a CTF-competition for my University. Where one of our challenges will utilize a Caesar Cipher to solve one of the basic flags. While creating the code that'll create our ciphered text I noticed that a quite common way of creating a Caesar cipher program is to utilize the string library.

More specific they'll first check if the letter is uppercase or lowercase or defining a list of accepted "alphabets"

ex. of this would be

import string

def caesar(text, shift, alphabets):

    def shift_alphabet(alphabet):
        return alphabet[shift:] + alphabet[:shift]

    shifted_alphabet = tuple(map(shift_alphabet, alphabets))
    final_alphabet = ''.join(alphabets)
    final_shifted_alphabet = ''.join(shifted_alphabet)
    table = str.maketrans(final_alphabet, final_shifted_alphabet)
    return text.translate(table)

message = "This is a message."
print(caesar(message, 7, [string.ascii_uppercase, string.ascii_lowercase, string.punctuation]))

My knowledge of strings (and that I've test run it using string.ascii_letters ) is that I can archive the same result using said string.ascii_letters instead of checking for if uppercase or lowercase.

What I can't find an answer for is that why one would decide to do it this way instead of using the catch all .ascii_letters .

Is there a performance penalty? Or simply good practice to check individually?

I think a lot of people just do it that way, because thats how you would do it in other programming languages.

In python you can utilize a lot of build in functions. A clean solution (in my opinion) is doing it this way

def shift_cipher(text: str, shift: int) -> str:
    """
    1. normalize the shift
    2.  shift the ASCII-alphabet:
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        -> 'defghijklmnopqrstuvwxyzabcDEFGHIJKLMNOPQRSTUVWXYZABC'
    3.  make a translation table and then translate the String
    """
    shift = shift % 26  # normalize shift
    alpha = string.ascii_letters
    alpha_shifted = alpha[shift:26] + alpha[:shift] + alpha[26 + shift:] + alpha[26:26 + shift]
    shift_table = text.maketrans(alpha, alpha_shifted)
    return text.translate(shift_table)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM