问题描述:
读取一个词语和一个位移数字,将词语中的字母向后平移输入数字的位数(ord and char可以将数字和字符串相互转化)
(第一次写的代码)
g=input('print a string\n')
ga=input('the number you want to move is:\n')#读取两个参量
def rotate_word(g,ga):
n=len(g)
ne=g
neq=g
for i in range(n):
if ord(g[i]) < 123-ga: #这里的chr(122)代表小写字母z
ne[i]=chr(ord(neq[i])+ga)
else:
ne[i]=chr(ord(neq[i])+ga-26)
#遍历字母,位移
print("the answer is",ne)
rotate_word(g,ga)
错误: input只能读取字符串,所以输入的位移位数被视为字符串,函数中相加出现问题
字符串一旦定义之后就不能更改,一开始应该定义成list类型
改后:
g=input('print a string')
ga=int(input('the number you want to move is:\n'))
def rotate_word(g,ga):
n=len(g)
ne=list(g)
neq=g
for i in range(n):
if ord(g[i]) < 123-ga:
ne[i]=chr(ord(neq[i])+ga)
else:
ne[i]=chr(ord(neq[i])+ga-26)
print("the answer is",ne)
rotate_word(g,ga)