Caesar Cipher

  • + 0 comments

    Python

    from itertools import cycle, islice
    
    def caesarCipher(s, k):
        if k == 0: return s
            
        # shift alphabet
        alpha = string.ascii_lowercase
        shifted = list(islice(cycle(alpha),
                              k, k+len(alpha)
                              ))
        
        s_shift = []
        for char in s:
            # uppercase flag
            upper = False
            if char.isupper():
                upper = True
                char = char.lower()
                
            # handling non-letters
            match = re.match(r'\W', char)
            if match or char.isnumeric() or char == '_':
                s_shift.append(char)
                
            # cipher
            else:
                idx = alpha.index(char)
                new_char = str(shifted[idx])
                if upper: new_char = new_char.upper()
                s_shift.append(new_char)
    						
        return str(''.join(s_shift))