简体   繁体   English

rot13不旋转'b'

[英]rot13 not rotating 'b'

Here is a rot13 func in python: 这是python中的rot13函数:

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 ? 为什么它将bo转换为bb而不是ob If you enter b alone it gets translated to o . 如果仅输入b ,它将转换为o

Because str.replace() replaces all instances of that character, even ones you've already replaced. 因为str.replace()替换该字符的所有实例,即使您已经替换了这些实例。 Generate a new string from the replacements instead of modifying the existing string. 从替换生成一个新字符串,而不是修改现有字符串。

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. 由于它不使用replace,因此不会遇到@Ignacio正确指出的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM