Search code examples
pythonencryptionappendascii

How would I add a space character to ascii_lowercase


So im making a code that'll encrypt a character or word per se. Im done with that so far but would like to include a space character and continue on with an extra word to encrypt. "Congratulations you won"<<<

from random import shuffle
from string import ascii_lowercase
array=[0]*26

for i in range(26):
    array[i]=i
shuffle(array)
let=ascii_lowercase
get=input("Give me a word to encrypt: ")
encrypt=""


for i in range(len(get)):
    
    ind=ord(get[i])-97
    
    print(get[i],ind,array[ind],let[array[ind]])
    
    encrypt=encrypt+let[array[ind]]
print(encrypt)

Code above

Something i would want would be like this

Give me a word to encrypt: congrats
c 2 6 g
o 14 22 w
n 13 9 j
g 6 5 f
r 17 19 t
a 0 25 z
t 19 14 o
s 18 1 b

y 24 13 f
o 14 22 w
u 20 15 e

w 22 12r
o 14 22 w
n 13 9 j

gwjftzob fwe rwj

i don't expect those exact results as its meant to be randomized/ shuffled

I attempted to use .append and .join to include space in ascii_lowercase but failed :')


Solution

  • Use + to concatenate strings.

    let = ascii_lowercase + " "
    

    Then replace ord(get[i]) - 97 with the value of let.index(get[i]), since that formula only works for lowercase letters.

    You also need to increase the length of array to 27, to add a place for the encrypted spaces.

    from random import shuffle
    from string import ascii_lowercase
    
    array=list(range(27))
    shuffle(array)
    
    let=ascii_lowercase + " "
    
    get=input("Give me a word to encrypt: ")
    encrypt=""
    
    for c in get:
        ind=let.find(c)
        if ind != -1:
            print(c,ind,array[ind],let[array[ind]])
            encrypt += let[array[ind]]
        else:
            # if it's not a letter or space, don't change it
            encrypt += c
    
    print(encrypt)