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

无法排查Python中TypeError: 'int' object is not subscriptable错误原因

解决TypeError: 'int' object is not subscriptable错误
  • 错误原因:你将输入内容转换为整数int后,尝试用下标(如[0]、[-1])访问其首尾字符,但整数类型不支持下标操作,因此触发该错误。
  • 修复方案:
    1. 直接保留输入的字符串格式,跳过不必要的整数转换:
      n = int(input())
      for i in range(n):
          s = input().strip()
          if s[0] == s[-1]:
              print("YES")
          else:
              print("NO")
      
    2. 若需同时进行数值计算和字符串检查,先存储原始字符串再转换为整数:
      n = int(input())
      for i in range(n):
          s = input().strip()
          num = int(s)
          # 此处可使用num执行数值相关操作
          if s[0] == s[-1]:
              print("YES")
          else:
              print("NO")
      
  • 你之前的转换操作误区:错误地在将输入转为整数后再尝试下标访问,这本身逻辑矛盾——整数没有下标属性。正确的转换时机是先保留字符串用于检查首尾,再按需转为整数。

内容的提问来源于stack exchange,提问作者Timothy Carroll

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:40:39