pythonpython-3.xvigenere

How to generate key in Vigenère cipher which avoid punctuation marks


I have to write Vigenère cipher but I have a problem. How to modify code to get key which ignore space, enter, comma, etc?

def generateKey(string, key):
    key = list(key)
    x = []
    if len(string) == len(key):
        return (key)
    else:
        for i in range(len(string)):
            x.append(key[i % len(key)])
    return ("".join(x))


    m = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor 
    incididunt ut labore et dolore magna aliqua."
    k = 'test'
    key = generateKey(m,k)
    print(key)

Input:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Output:

testtesttesttesttesttesttesttesttesttesttesttesttesttest

I want this:

testt estte sttes tes ttes, ttesttestte sttesttest test, tes tt esttest testte sttesttest testte st testte sttes ttestt.

Solution

  • Probably str.isalpha is what you need.

    def generate_key(string, key):
        key_len = len(key)
        if len(string) == key_len:
            return key
        x = []
        i = 0
        for char in string:
            if char.isalpha():
                x.append(key[i % key_len])
                i += 1
            else:
                x.append(char)
        return "".join(x)
    
    m = ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor" 
         "incididunt ut labore et dolore magna aliqua.")
    k = 'test'
    key = generate_key(m,k)
    print(key)
    # 'testt estte sttes tte stte, sttesttestt esttesttes ttes, tte st testtes ttestt esttesttes tt esttes tt esttes ttest testte.'
    

    To be more pythonic and avoid index manipulations, you can use itertools.cycle:

    from itertools import cycle
    
    def generate_key(string, key):
        if len(string) == len(key):
            return key
        key_iter = cycle(key)
        return ''.join(next(key_iter) if char.isalpha() else char for char in string)
    

    Note there's an error in your expected output (missing "t" in 4th word).