Thilo 准确地解释了这个问题。让我们一步一步来:
''' Cesar Cipher '''
def encrypt(word, shift):
word = word.lower()
for i in word:
r = chr(ord(i)+shift)
if r > "z":
r = chr(ord(i) - 26 + shift)
word = word.replace(i, r)
return word
试试看encrypt('abc', 1)
会发生什么:
First loop:
i = 'a'
r = chr(ord('a')+1) = 'b'
word = 'abc'.replace('a', 'b') = 'bbc'
Second loop:
i = 'b'
r = chr(ord('b')+1) = 'c'
word = 'bbc'.replace('b', 'c') = 'ccc'
Third loop:
i = 'c'
r = chr(ord('c')+1) = 'd'
word = 'ccc'.replace('c', 'd') = 'ddd'
您不想替换with的每个实例,只是这个。你会怎么做?好吧,如果您跟踪索引,则可以在该索引处进行替换。内置函数可让您同时获取每个索引和每个对应值。i
r
enumerate
for index, ch in enumerate(word):
r = chr(ord(ch)+shift)
if r > "z":
r = chr(ord(ch) - 26 + shift)
word = new_word_replacing_one_char(index, r)
现在你只需要编写那个new_word_replacing_one_char
函数,如果你知道切片,这很容易。(如果你还没有学过切片,你可能想把字符串转换成一个list
字符,所以你可以说word[index] = r
,然后在最后再转换回一个字符串。)