Welcome, guest | Sign In | My Account | Store | Cart

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 :)

Python, 8 lines
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)

2 comments

Tom Good 22 years, 3 months ago  # | flag

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 :)

Created by anurag uniyal on Wed, 9 Jan 2002 (PSF)
Python recipes (4591)
anurag uniyal's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks