You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

判断字符串首尾字符是否相同的Python函数报错排查及修正

问题排查与修复

错误原因

  1. 索引越界触发报错:空字符串没有任何字符,直接访问message[0]或message[-1]会触发IndexError,这是报错的直接原因。
  2. 条件判断顺序错误:原函数把空字符串的判断放在最后一个elif分支,而前面的分支已经先尝试访问字符串索引,导致空字符串的情况根本没机会进入对应的处理分支。

修复后的代码

def first_and_last(message):
    # 优先处理空字符串的边界情况
    if not message:
        return False
    # 非空字符串直接判断首尾字符是否相同
    return message[0] == message[-1]

print(first_and_last("else"))  # 输出 True
print(first_and_last("tree"))  # 输出 False
print(first_and_last(""))      # 输出 False,无报错

代码说明

  • if not message:利用空字符串在布尔上下文中等价于False的特性,快速判断并处理空字符串的情况,避免后续索引访问。
  • 非空字符串直接返回message[0] == message[-1]的结果,简化了冗余的if-elif判断逻辑。

内容的提问来源于stack exchange,提问作者Nana Owusu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:10:32