鱼C论坛

 找回密码
 立即注册
查看: 1604|回复: 2

[已解决]关于Python字符串反码

[复制链接]
发表于 2023-9-25 17:48:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

请问这是什么原因?
最佳答案
2023-9-25 17:48:26
这个错误是由于在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 。

希望这个解释对你有帮助!如果你还有其他问题,请随时提问。

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-9-25 17:48:26 | 显示全部楼层    本楼为最佳答案   
这个错误是由于在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 。

希望这个解释对你有帮助!如果你还有其他问题,请随时提问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-9-25 17:52:26 | 显示全部楼层
isdkz 发表于 2023-9-25 17:48
这个错误是由于在while循环中的条件判断出现了问题导致的。

在条件判断中,你使用了连续的比较运算符

感谢!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 11:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表