我在写代码,所以你可以把文字沿字母表移动两个位置:“ab cd”应该变成“cd ef”。我正在使用Python 2,这是我目前所得到的:
def shifttext(shift):
input=raw_input('Input text here: ')
data = list(input)
for i in data:
data[i] = chr((ord(i) + shift) % 26)
output = ''.join(data)
return output
shifttext(3)
我得到以下错误:
File "level1.py", line 9, in <module>
shifttext(3)
File "level1.py", line 5, in shifttext
data[i] = chr((ord(i) + shift) % 26)
TypError: list indices must be integers, not str
所以我得把字母改成数字?但我以为我已经做到了?
马蒂金的回答很好。这里有另一种实现相同目标的方法:
您在字符列表上循环,因此
i
是一个字符。然后尝试使用i
字符作为索引将其存储回data
。那不行。使用
enumerate()
获取索引和值:可以使用生成器表达式简化此过程:
但是现在你会注意到你的
% 26
不起作用;ASCII代码点在26之后开始:您需要使用
ord('a')
值来代替使用模数;减法将您的值置于0-25的范围内,然后再添加:但这只适用于小写字母;这可能很好,但您可以通过将输入小写来强制:
如果我们从函数中请求输入,将其集中在做好一项工作上,这将变成:
在交互提示下使用这个,我看到:
当然,现在标点符号也被采用了。上一次修订,现在只更改字母:
我们得到:
看来你在做塞萨尔密码加密,所以你可以试试这样的方法:
输出:
strs[(strs.index(i) + shift) % 26]
:上面的行表示在strs
中找到字符i
的索引,然后向其添加移位值。现在,在最终值(index+shift)上应用%26来获取移位索引。当传递到strs[new_index]
时,这个移位索引产生所需的移位字符。相关问题 更多 >
编程相关推荐