|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- s=input()
- i=0
- j=0
- len=len(s)
- str0=[0]*len
- while(i-1<=len):
- if(65<=ord(s[i])<=77):
- temp1=ord(s[i])
- temp2=ord('Z')-(temp1-ord('A'))
- str0[i]=s[i].replace(s[i],str(temp2))
- i+=1
- elif(78<=ord(s[i])<=90):
- temp1=ord(s[i])
- temp2=ord('A')+(ord('Z')-temp1)
- str0[i]=s[i].replace(s[i],str(temp2))
- i+=1
- elif(97<=ord(s[i])<=109):
- temp1=ord(s[i])
- temp2=ord('z')-(temp1-ord('a'))
- str0[i]=s.replace(s[i],str(temp2))
- i+=1
- elif(110<=ord(s[i])<=122):
- temp1=ord(s[i])
- temp2=ord('a')+(ord('z')-temp1)
- str0[i]=s[i].replace(s[i],str(temp2))
- i+=1
- else:
- i+=1
- print(str0)
复制代码
输入:CD 后报错:- if(65<=ord(s[i])<=77):
- ~^^^
- IndexError: string index out of range
复制代码
请问这是什么原因?
这个错误是由于在while循环中的条件判断出现了问题导致的。
在条件判断中,你使用了连续的比较运算符 <= 和 <= ,但是这种写法在Python中是不支持的。
正确的写法应该是使用逻辑运算符 and 来连接多个条件判断,如下所示:
- if 65 <= ord(s[ i]) and ord(s[ i]) <= 77:
- # do something
- elif 78 <= ord(s[ i]) and ord(s[ i]) <= 90:
- # do something
- elif 97 <= ord(s[ i]) and ord(s[ i]) <= 109:
- # do something
- elif 110 <= ord(s[ i]) and ord(s[ i]) <= 122:
- # do something
- else:
- # do something
复制代码
请注意,这里的条件判断需要使用逻辑运算符 and 连接两个判断条件,以确保两个条件都为真时才执行相应的代码。
另外,你的while循环的终止条件应该是 i < len ,而不是 i-1 <= len 。这是因为索引是从0开始的,所以最后一个元素的索引是 len-1 。
希望这个解释对你有帮助!如果你还有其他问题,请随时提问。
|
|