A variation on your code so that the spaces (and other characters) remain as such, could be in a variable a string that contains all the characters to be respected, and copy to cipher
the current character if it is between them . That is:
alfa="abcdefghijklmnopqrstuvwxyz"
cipher = ""
no_tocar = " .,¿?!¡:;()"
for c in G:
if c in no_tocar:
cipher += c
elif c in alfa:
# ... el resto igual
Another detail, do not close the file ar
. Precisely so as not to forget those kind of details, it is recommended to use a context, that is:
with open('prueba.txt', 'r') as ar:
G = ar.read()
The file is automatically closed when you exit the with
block.
A final detail related to efficiency, in code you have to build a letter by letter (or word by word) string, it is preferable to use intermediate lists instead of the operator +=
on the string.
That is, cipher
would be an initially empty list ( cipher=[]
) to which you are adding letters ( cipher.append(letra)
). At the end of the loop cipher
will be a list with the letters already converted, from which you generate the result string with cipher = "".join(cipher)
. This is faster than using the operator to concatenate in each iteration.