Looping for every character in a string in Python decoder ring

user1063543 picture user1063543 · Nov 24, 2011 · Viewed 43.5k times · Source

I'm trying to make a simple decoder ring in Python.

Example:

a=b, `b=c, c=d, etc.  

I want the script to take an encoded message and output the decoded message.
For instance, I would input "ifmmp" and it would output "hello".

I've been thinking I need to split all the characters up and loop through them and change their chr() or ord() values.

There doesn't seem to be any documentation for this in python.

Answer

Some programmer dude picture Some programmer dude · Nov 24, 2011

How about:

s = 'ifmmp'
new_s = ''
for c in s:
    n = ord(c)
    n = n - 1
    if n < ord('a'):
        # 'a' -> 'z'
        n = ord('z')
    new_s += chr(n)
# print('new_s = %r' % new_s)  -> new_s = 'hello'

Of course, this is only handling small letters, not capital.