Script to replace characters in file
Question: i'm facing trouble trying to replace characters in a file.

    
    
        #!/usr/bin/env python
    
    with open("crypto.txt","r") as arquivo:
        data =  arquivo.read()
    for caracter in data:
        if "a" in data:
            data = data.replace("a","c")
        elif "b" in data:
            data = data.replace("b","d")
        elif "c" in data:
            data = data.replace("c","e")
        elif "d" in data:
            data = data.replace("d","f")
        elif "e" in data:
            data = data.replace("e","g")
        elif "f" in data:
            data = data.replace("f","h")
        elif "g" in data:
            data = data.replace("g","i")
        elif "h" in data:
            data = data.replace("h","j")
        elif "i" in data:
            data = data.replace("i","k")
        elif "j" in data:
            data = data.replace("j","l")
        elif "k" in data:
            data = data.replace("k","m")
        elif "l" in data:
            data = data.replace("l","n")
        elif "m" in data:
            data = data.replace("m","o")
        elif "n" in data:
            data = data.replace("n","p")
        elif "o" in data:
            data = data.replace("o","q")
        elif "p" in data:
            data = data.replace("p","r")
        elif "q" in data:
            data = data.replace("q","s")
        elif "r" in data:
            data = data.replace("r","t")
        elif "s" in data:
            data = data.replace("s","u")
        elif "t" in data:
            data = data.replace("t","v")
        elif "u" in data:
            data = data.replace("u","w")
        elif "v" in data:
            data = data.replace("v","x")
        elif "w" in data:
            data = data.replace("w","y")
        elif "x" in data:
            data = data.replace("x","z")
        print data
    

the script reads a txt file called crypto and start to replace the characters
based on the statements above. Inside the file is writed the word aloha.

this is the result i get everytime i run the script

    
    
    clohc
    elohe
    glohg
    ilohi
    iloji
    klojk
    

how can i fix it?


Answer: What about python's [ string
translate](https://docs.python.org/3/library/stdtypes.html#str.translate)

    
    
    import string
    with open("crypto.txt","r") as arquivo:
        data =  arquivo.read()
        out = data.translate(string.maketrans("abcdefghijklmnopqrstuvw","defghijklmnopqrstuvwxyz"))
        print out
    

It is directly equlal to perl `tr` function. It is works as below

Image describes `A` convert to `T`, `C` convert to `G`, `G` convert to `C` and
`T` convert to `A`

[![](http://i.stack.imgur.com/Btr3b.png)](http://i.stack.imgur.com/Btr3b.png)

> **Then don't get confuse with string translate and string replace**

string replace, replace the whole word. string translate, replace by the each
character.

