Kraig Clubb
Kraig Clubb

Reputation: 87

Python Caesar Cipher keeping spaces

I need help keeping the spaces. I have the caesar cipher functioning, but I want it to keep the spaces and can't figure out how to do that.

sentence = raw_input("Please enter a sentence : ").lower()
newString = ''
validLetters = "abcdefghijklmnopqrstuvwxyz"
space = [ ]
for char in sentence:
    if char in validLetters or char in space:
        newString += char
        shift = input("Please enter your shift : ")
        resulta = []
for ch in newString:
    x = ord(ch)
    x = x + shift
    resulta.append(chr(x if 97 <= x <= 122 else 96 + x % 122))
print sentence
print("")
print("Your encryption is :")
print("")
print ''.join(resulta)

It outputs correct code but removes the spaces. How can I keep the spaces on encryption?

Upvotes: 1

Views: 6547

Answers (2)

Acuda
Acuda

Reputation: 66

If you don't want to encrypt the spaces, this works for me:

sentence = raw_input("Please enter a sentence : ").lower()
newString = ''
validLetters = "abcdefghijklmnopqrstuvwxyz " #adding whitespace to valid chars...
space = []
for char in sentence:
    if char in validLetters or char in space:
        newString += char
shift = input("Please enter your shift : ")
resulta = []
for ch in newString:
    x = ord(ch)
    x = x+shift
    # special case for whitespace...
    resulta.append(chr(x if 97 <= x <= 122 else 96+x%122) if ch != ' ' else ch)
print sentence
print("")
print("Your encryption is :")
print("")
print ''.join(resulta)

a little bit shorter, but still your way:

sentence = raw_input("Please enter a sentence : ").lower()
shift = input("Please enter your shift : ")

validLetters = map(chr, range(97, 123))
validLetters.append(' ')

tmp = [ord(ch)+shift for ch in sentence if ch in validLetters]
resulta = [chr(x if 97 <= x <= 122 else 96+x%122) if x != ord(' ')+shift else ' ' for x in tmp]

print sentence
print
print("Your encryption is :")
print
print ''.join(resulta)

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113950

>>> key = string.ascii_lowercase
>>> rotation = 13
>>> tab = string.maketrans(key,key[rotation:]+key[:rotation])
>>> "hello world".translate(tab)
'uryyb jbeyq'

Upvotes: 6

Related Questions