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

Python代码触发TypeError的原因咨询:字符串索引变量类型异常

问题原因分析

你触发TypeError的核心原因是**for i in string这个循环逻辑错误**——你以为这里的i是整数索引,但Python遍历字符串时,for循环会直接取出字符串里的每一个字符,而非索引位置。比如输入"hello",循环里的i会依次是"h"、"e"、"l"、"l"、"o",此时用string[i]相当于拿字符当索引,而字符串的索引必须是整数,自然会触发TypeError。

修正后的代码
# 获取用户输入的字符串
user_string = input("Enter a phrase: ")

# 初始化存储连续重复字符的变量
double_occurrences = ""

# 遍历字符串索引,留最后一个位置给j=i+1,避免越界
for i in range(len(user_string) - 1):
    j = i + 1
    if user_string[i] == user_string[j]:
        # 添加连续重复的字符
        double_occurrences += user_string[i] + user_string[j]

# 处理无重复的情况
if not double_occurrences:
    double_occurrences = "N/A"

# 输出结果
print(f"Your input contains the following double occurrences: {double_occurrences}")
关键修改说明
  • 循环改为for i in range(len(user_string)-1):让i变成整数索引,范围从0到字符串长度减2,确保j=i+1不会超出字符串边界。
  • 移除冗余的j初始化与递增操作:直接在循环内定义j=i+1,逻辑更清晰,避免出现j越界的问题。
  • 简化重复字符的存储逻辑:初始设为空字符串,无重复时再替换为"N/A",比原代码的替换操作更直观。
  • 变量名调整为符合Python规范的命名:提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:16:06