Search code examples
pythonencryptioncaesar-cipher

Encryption Python - encrypting a string


Using this program to take out spaces, punctuation, and make letters lower case...

def pre_process(s):
    s= s.replace("'","")
    s= s.replace('.','')
    s= s.lower()
    s= s.replace(" ","")
    return s

How can I encrypt a message (s) so that the letters each shift by an amount equal to the corresponding letter in the alphabet? ex) 'm' shifted 5 becomes 'r' but 'w' shifted 5 becomes 'b'?


Solution

  • This may be helpful to you...Just change the value of shifter in encrypt function to get the corresponding shift

    def shift(char,shift_by):
        val=ord(char) #gives ascii value of charecter
        val+=shift_by
        if(val>122):
            val=97+(val-122-1)
        return(chr(val))
    
    def encrypt_string(str):
        shifter=2 #change to value of shifter here
        encrypted_string=""
        for i in str :
            if( (ord(i)>=97) and (ord(i)<=122) ):
                i=shift(i,shifter)
            encrypted_string+=i
        return(encrypted_string)