from string import maketrans table = maketrans('abcdefghijklmnopqrstuvwxyz/','zabcdefghijklmnopqrstuvwxy ') for x in ('pdfbo','qipophsbqi','cmvf/nppo/jo/b/sfe/tlz'): print x,' -> ',x.translate(table)
result
pdfbo -> ocean qipophsbqi -> phonograph cmvf/nppo/jo/b/sfe/tlz -> blue moon in a red sky
.
Edit
I rewrote the Joachim algorithm (the function is better () ), and I wrote my own solution without using maketrans () ( yop () ):
s = '{ifmmp}\t\tcmvf-nppo \n SUNNY ~ ajhabh 14568' def bof(s): 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) return new_s def better(s): li = [] for c in s: n = ord(c)-1 if n == 96: li.append('z') elif 96<n<122: li.append(chr(n)) else: li.append(c) return ''.join(li) def yop(s): gen = ((c,ord(c)-1) for c in s) return ''.join('z' if y==96 else chr(y) if 96<y<122 else x for x,y in gen) def better_yop(s): def gen(h): for c in h: n = ord(c)-1 if n == 96: yield 'z' elif 96<n<122: yield chr(n) else: yield c return ''.join(gen(s)) for truc in (s,bof(s),better(s),yop(s),better_yop(s)): print '%r\n%s\n' % (truc,truc)
result
'{ifmmp}\t\tcmvf-nppo \n SUNNY ~ ajhabh 14568' {ifmmp} cmvf-nppo SUNNY ~ ajhabh 14568 'zhello|zzbluezmoonzzzzzzzzz}zzigzagzzzzzz' zhello|zzbluezmoonzzzzzzzzz}zzigzagzzzzzz '{hello}\t\tblue-moon \n SUNNY ~ zigzag 14568' {hello} blue-moon SUNNY ~ zigzag 14568 '{hello}\t\tblue-moon \n SUNNY ~ zigzag 14568' {hello} blue-moon SUNNY ~ zigzag 14568 '{hello}\t\tblue-moon \n SUNNY ~ zigzag 14568' {hello} blue-moon SUNNY ~ zigzag 14568
However, my yop () function is slower than the better () function
.
Edit
The better_yop () function now has a speed equivalent to better ()
However, better () seems a little faster than better_yop () . Since it is also simpler, better () is better
eyquem
source share