One liner code to shift each char of a string by some passed value very simple encryption :) added version 2 fixing following bugs: 1. Capital chars are shifted correctly. 2. Only alpha numeric chars are shifted. 3. No hard-coded numbers so that as long as first alphabet is 'a' and last 'z' it will work :)
1 2 3 4 5 6 7 8 | shift = lambda text,sft=1:string.joinfields(map(eval("lambda ch:chr((ord(ch)-ord('a')+%d)%%26+ord('a'))"%(sft,)),text),'')
shift2 = lambda txt,sft=1:''.join([[ch,chr((ord(ch) - ord(['A','a'][ch.islower()]) + sft)%26+ord(['A','a'][ch.islower()]))][ch.isalpha()] for ch in txt])
#test
print shift2('Ab-Phkew! 123...',7)
for i in range(26):print shift2('abcdefghijklmnopqrstuvwxyz',i)
|
Tags: algorithms
good. That's a good one-liner. Using %s to insert the literal % is not really necessary ("%%" does the same thing), so you could trim it down to this:
shift = lambda text,sft=1:string.joinfields(map(eval("lambda ch:chr((ord(ch)-ord('a')+%d)%%26+ord('a'))"%sft),text),'')
thanks! changed. i changed '%s'%('%') to '%%' and added a test function :)