Encrypting a text file but leaving the space in?

702 views Asked by At

I've successfully managed to create a code which encrypts the text file using the randomly generated offset factor earlier in the program but I don't know how to leave the spaces where they are without encrypting them?

text_file = open("sample.txt", "r")

characters = []
for line in text_file:
    for c in line:
        characters.append(c)

text_ascii = []
text_number = 0
new_number = 0
cipher_text = ""
for i in characters:
    if i not in (" "):
        text_ascii = ord(i)
        text_number = text_ascii + offset_factor
        if text_number > 126:
            text_number = text_number - 94
        new_number = chr(text_number)
        cipher_text = cipher_text + new_number

print (cipher_text)

The code I have now doesn't encrypt the spaces or include them at all.

The content of the text file (called 'sample.txt' and all on one line) is:

Somewhere in la Mancha, in a place whose name I do not care to remember, a gentleman lived not long ago, one of those who has a lance and ancient shield on a shelf and keeps a skinny nag and a greyhound for racing.

2

There are 2 answers

0
Frank Toner On

that will work, but i would suggest that you use the function maketrans, and translate, in python 3+ you must use str.maketrans and str.translate, but python 2.x you must import string and use string.maketrans and string.translate. using these functions, python allows for a very efficient, short and easy to follow caesar cipher encryption method...

message = input('enter message').lower()
offset = int(input('enter offset (enter a negative number to decrypt)'))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+alphabet[0:offset]
data = str.maketrans(alphabet,enc_alphabet)
final_message = str.translate(message, data)
print(final_message)
0
Ignacio Vazquez-Abrams On

You forgot to handle the case where it is a space.

if ...:
   ...
else:
  cipher_text += ' '