-1

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'?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
User
  • 29
  • 3
  • possible duplicate of [How to make shift('w','f') return 'b'?](http://stackoverflow.com/questions/28756582/how-to-make-shiftw-f-return-b) – Cristian Ciupitu Feb 27 '15 at 19:26

2 Answers2

1

You have to do some ord and chr tricks to do what you want. Basically, these two functions return the integer representation of your letters, and outputs the corresponding letter of the integer representation, respectively.

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

    mystring = ""
    for letter in s:
        shift = 5
        r = ord(letter)+shift
        if (r > ord('z')):
            r -= 26
        mystring += (chr(r))
    return mystring
Secret
  • 3,291
  • 3
  • 32
  • 50
0

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)
Aakash
  • 83
  • 1
  • 12
  • `if(...)`, `return(...)` works, but it's ugly by Python's standards i.e. [PEP 8](https://www.python.org/dev/peps/pep-0008/). `(ord(i)>=97) and (ord(i)<=122)` can be replaced with `97 <= ord(i) <=122`. – Cristian Ciupitu Feb 27 '15 at 19:28
  • Yes,you are totally correct...I guess it will take a while to drop my C coding style :) – Aakash Feb 27 '15 at 19:59