I want to convert a single character of a string into an integer, add 2 to it, and then convert it back to a string. Hence, A becomes C, K becomes M, etc.
http://docs.python.org/library/functions.html
ord(c)
Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a TypeError will be raised.
This sounds a lot like homework, so I'll give you a couple of pieces and let you fill in the rest.
To access a single character of string s, its s[x] where x is an integer index. Indices start at 0.
To get the integer value of a character it is ord(c) where c is the character. To cast an integer back to a character it is chr(x). Be careful of letters close to the end of the alphabet!
Edit: if you have trouble coming up with what to do for Y and Z, leave a comment and I'll give a hint.
Normally, Just ord and add 2 and chr back, (Y, Z will give you unexpected result ("[","\")
>>> chr(ord("A")+2)
'C'
If you want to change Y, Z to A, B, you could do like this.
>>> chr((ord("A")-0x41+2)%26+0x41)
'C'
>>> chr((ord("Y")-0x41+2)%26+0x41)
'A'
>>> chr((ord("Z")-0x41+2)%26+0x41)
'B'
Here is A to Z
>>> [chr((i-0x41+2)%26+0x41) for i in range(0x41,0x41+26)]
['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B']
For a whole string this would be:
>>> s = "Anne"
>>> ''.join([chr(ord(i)+2) for i in s])
'Cppg'
It's diffucult for 'Y', 'Z' ...
>>> s = "Zappa"
>>> ''.join([chr(ord(i)+2) for i in s])
'\\crrc'
"ord" is only part of the solution. The puzzle you mentioned there rotates, so that "X"+3 rotates to "A". The most famous of these is rot-13, which rotates 13 characters. Applying rot-13 twice (rotating 26 characters) brings the text back to itself.
The easiest way to handle this is with a translation table.
import string
def rotate(letters, n):
return letters[n:] + letters[:n]
from_letters = string.ascii_lowercase + string.ascii_uppercase
to_letters = rotate(string.ascii_lowercase, 2) + rotate(string.ascii_uppercase, 2)
translation_table = string.maketrans(from_letters, to_letters)
message = "g fmnc wms bgblr"
print message.translate(translation_table)
Not a single ord() or chr() in here. That's because I'm answering a different question than what was asked. ;)