看起来您正在进行cesar密码加密,因此您可以尝试执行以下操作:
strs = 'abcdefghijklmnopqrstuvwxyz' #use a string like this, instead of ord()
def shifttext(shift):
inp = raw_input('Input text here: ')
data = []
for i in inp: #iterate over the text not some list
if i.strip() and i in strs: # if the char is not a space ""
data.append(strs[(strs.index(i) + shift) % 26])
else:
data.append(i) #if space the simply append it to data
output = ''.join(data)
return output
In [2]: shifttext(3)
Input text here: how are you?
Out[2]: 'krz duh brx?'
In [3]: shifttext(3)
Input text here: Fine.
Out[3]: 'Flqh.'
strs[(strs.index(i) + shift) % 26]
:线以上手段找到字符的索引i
中strs
,然后添加移位值it.Now,对最终值(索引+偏移)申请%26向得到移位索引。传递给时,此移位索引会strs[new_index]
产生所需的移位字符。