Search code examples
pythonrot13

rot13 not rotating 'b'


Here is a rot13 func in python:

from string import ascii_lowercase

def rot13(string):
    l = list(ascii_lowercase)
    nl = [l[:13],l[13:]]
    tr_dict1 = dict(zip(nl[0], nl[1]))
    tr_dict2 = dict(zip(nl[1], nl[0]))
    #print tr_dict1
    #print tr_dict2
    for char in string:
        if char in tr_dict1:
            string = string.replace(char, tr_dict1[char])
        if char in tr_dict2:
            string = string.replace(char, tr_dict2[char])
    print string

string = raw_input('Enter string: ')
rot13(string)

Why does it translate bo to bb instead of ob? If you enter b alone it gets translated to o.


Solution

  • Because str.replace() replaces all instances of that character, even ones you've already replaced. Generate a new string from the replacements instead of modifying the existing string.