I am trying to modify a string , by replacing each alphabet by an alphabet which is two postions ahead of it. e.g. 'a' replaced by 'c', 'b' replaced by 'd'. The only exceptions is 'y' should be replaced by 'a' and 'z' by 'b' (loops back to start).
I have written the following code for it, which seems to serve the purpose, but the output formatting kind of spoils it.
string = "g fmnc wms bgblr rpylqjyrc gr zw fylb."
print string
for i in string:
if i.isalpha():
if ord(i)>120:
print chr(ord(i)-24),
else:
print chr(ord(i)+2),
else:
print i
Output :
g fmnc wms bgblr rpylqjyrc gr zw fylb.
i h o p e y o u d i d n t t r a n s l a t e i t b y h a n d .
Expected Output:
g fmnc wms bgblr rpylqjyrc gr zw fylb.
i hope you didnt translate it by hand.
Is there any alternative, quicker approach to solve this?
from string import translateand use it.intab = "abcdefghijklmnopqrstuvwxyz" outtab= "cdefghijklmnopqrstuvwxyzab" trantab = maketrans(intab, outtab) print string.translate(trantab)