python - How can i make sure that all punctuation isn't encrypted? -


        n in range(0, len(plaintext)):             if plaintext[n] == ' ':                 new = ord(plaintext[n])             else:                 new = ord(plaintext[n]) + ord(key[n%len(key)]) - 65                 if new > 90: 

so want know how can make sure punctuation isn't encrypted , letters encrypted? know isn't way encrypt school project great if can me. when decrypt doesn't decrypt , forgets full stops , stuff how can fix this? thanks.

define punctuation;

punctuation = " ',.;:.!?\r\n" 

replace all instances of

if plaintext[n] == ' ': 

by

if plaintext[n] in punctuation: 

addition

while code functional, doesn't use lot of powerful tools python puts @ disposal. let me illustrate. encryption/decryption (with punctuation stripped text) done this, using list comprehensions;

in [42]: plaintext = 'thisisaplaintext' # algorithm works capitals.  in [43]: key = 'spameggs'  in [44]: count = int(len(plaintext)/len(key))+1  in [45]: stretchedkey = [ord(c) c in key*count]  in [46]: # encryption  in [47]: plainnum = [ord(c) c in plaintext]  in [48]: ciphernum = [a+b-65 a, b in zip(plainnum, stretchedkey)]  in [49]: ciphertext = ''.join([chr(c) if c <= 90 else chr(c-26) c in ciphernum])  in [50]: ciphertext out[50]: 'lwiemyghdpizxkdl'  in [51]: # decryption  in [52]: ciphernum = [ord(c) c in ciphertext]  in [53]: decryptnum = [a-b+65 a, b in zip(ciphernum, stretchedkey)]  in [54]: decrypt = ''.join([chr(c) if c >= 65 else chr(c+26) c in decryptnum])  in [55]: decrypt out[55]: 'thisisaplaintext' 

some explanations.

a list comprehension can convert string list of 1 character strings;

in [69]: [c c in 'thisisatext'] out[69]: ['t', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 'x', 't'] 

or list of character values;

in [70]: [ord(c) c in 'thisisatext'] out[70]: [84, 72, 73, 83, 73, 83, 65, 84, 69, 88, 84] 

you can strip out punctuation while that.

in [80]: [c c in 'this text.' if c not in ' .'] out[80]: ['t', 'h', 'i', 's', 'i', 's', 'a', 't', 'e', 'x', 't'] 

the zip built-in lets iterate on combinations of lists;

in [73]: p = [ord(c) c in 'thisisatext']  in [74]: q = [ord(c) c in 'spameggsspameggs']  in [77]: p out[77]: [84, 72, 73, 83, 73, 83, 65, 84, 69, 88, 84]  in [78]: q out[78]: [83, 80, 65, 77, 69, 71, 71, 83, 83, 80, 65, 77, 69, 71, 71, 83]  in [79]: [a+b a, b in zip(p, q)] out[79]: [167, 152, 138, 160, 142, 154, 136, 167, 152, 168, 149] 

hint:

make list of punctuation in string, index.

in [82]: [(n, c) n, c in enumerate('this text.') if c in ' .'] out[82]: [(4, ' '), (7, ' '), (9, ' '), (14, '.')] 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -