Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python rot13不旋转';b';_Python_Rot13 - Fatal编程技术网

Python rot13不旋转';b';

Python rot13不旋转';b';,python,rot13,Python,Rot13,以下是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

以下是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)

为什么它将
bo
翻译成
bb
,而不是
ob
?如果单独输入
b
,它将被转换为
o

,因为
str.replace()
将替换该字符的所有实例,即使是已替换的实例。从替换中生成新字符串,而不是修改现有字符串。

因为
str.replace()
替换该字符的所有实例,即使是已替换的实例。从替换中生成一个新字符串,而不是修改现有字符串。

这样替换字符可能会更容易:

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)

由于它不使用replace,因此它不会出现与@Ignacio正确指出的问题相同的问题。

您可能会更容易替换如下字符:

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)

因为它不使用replace,所以它不会出现与@Ignacio正确指出的问题相同的问题。

句子会失去空格。@koogee,你说得对。更新为使用空格或非字母字符。这很好。使用get并提供空格作为space+1entence的默认值将丢失间距。@koogee,你说得对。更新为使用空格或非字母字符。这很好。使用get和providing space作为space+1的默认值