Question

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.

Was it helpful?

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.

OTHER TIPS

You might have an easier time replacing the characters like this:

from string import ascii_lowercase

l = list(ascii_lowercase)
tr = dict(zip(l, l[13:] + l[:13]))

def rot13(inval):
    return "".join(tr.get(char, char) for char in inval)

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

Since it doesn't use replace, it will not have the same issue you ran into which @Ignacio correctly pointed out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top