the code must read a file type .txt and put it in cipher cease, the problem is that it takes away the spaces

0
r=2
while r==2:

    print("1. Cifrar \n")
    print("2. Decifrar\n")
    res = pos=int(input("Elige una opcion de las anteriores \n =>"))

    ar = open ('prueba.txt','r') #archivo que lee
    G = ar.read()
    print(G)# imprime texto que existe en el archivo




    alfa="abcdefghijklmnopqrstuvwxyz "
    k = pos=int(input("Numero de caracteres que deseas recorrer =>"))

    cipher = "" 
    for c in G:
            if c in alfa:


                if res==1:
                   cipher += alfa [(alfa.index(c)+k)%(len(alfa))]


                if res==2:
                    cipher += alfa [(alfa.index(c)-k)%(len(alfa))]

    print(cipher )
    print("1. Si")
    print("2. No")
    r= pos=int(input("¿Quiere salir? >>>"))
    if r==1:
        r==r-1
    
asked by Maico 22.02.2018 в 22:15
source

1 answer

0

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.

    
answered by 22.02.2018 в 22:49