0

I'm currently working on a program that both encrypts and decrypts code. I have three options in the menu that the user can choose, Encrypt, Decrypt or Extended Encrypt. I am having a problem with the extended encrypt.

Basically, to make the ciphertext harder for another person to decrypt, I would like to group it into groups of five letters, one way I thought of doing this was to put the base encrypted text into a string and go through every index and checking if it was divisible by five with a remainder of zero (modulo):

extend = "" 
for x in range(0, len(encrypted)): #encrypted would have its contents defined before hand
    if x % 5 == 0:
        extend = extend + " " #adds a space, could otherwise do + chr(32)
    else:
        extend = extend + encrypted[x]

When look at the outputted file, the file contains no extra spaces, its as though x % 5 never has a value of zero, so the line extend = extend + " " is never called.

Thanks in advance!

A.Tol
  • 33
  • 1
  • 8
  • Related: [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – GingerPlusPlus Mar 17 '16 at 17:55

2 Answers2

0

You can use a regexp:

import re
encrypted = 'abcdeabcde'
re.sub('(.{5})', '\\1 ', encrypted)

Returns:

 'abcde abcde '
A.P.
  • 1,109
  • 8
  • 6
0

This means that there are no numbers that when divided by 5 yield a whole number.

The following code shows that when `ranges is large enough, everything works fine.

for x in range(20):
    if not (x % 5): 
        print "Got it: {}".format(x)

Output:

Got it: 0
Got it: 5
Got it: 10
Got it: 15
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • @A.Tol, this is _the same_ as `(x % 5) == 0` – ForceBru Mar 17 '16 at 18:04
  • Thanks! Sorta makes sense now. Only thing is, the string was 10 characters long. It was "Encrypt Me" and the encrypted text went something like "A3f'yTp Rt" The space is exactly where it was, but the range is large enough so that it should get to five, and when five is divided by five, it should yield a whole number, right? – A.Tol Mar 17 '16 at 18:07
  • @A.Tol zero in a boolean context has a value of false so that is the same as asking `if n == 0`, the same aplícate string, list, tuple and other containers they all evaluate to false when they are empty, true otherwise, in a boolean context so you can do `if my_container` – Copperfield Mar 17 '16 at 18:12
  • @A.Tol, your code seems to work fine. When I run it I get this: `" 3f'y p Rt"`. There's a space inserted between `p` and `y` and `3` and at the beginning, so everything is working OK – ForceBru Mar 17 '16 at 18:13
  • This is weird, doesn't seem to work like that for me, my code would return the message "3f'yp rt" – A.Tol Mar 17 '16 at 18:47
  • @A.Tol, the code _from your question_ works fine, try to copy & paste it into your Python interpreter. – ForceBru Mar 17 '16 at 18:51