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

Python如何统计字符串中指定字符的出现次数?现有代码结果错误求解

问题排查

你代码的统计逻辑存在两处错误:

  • 变量重名覆盖:用户输入的待统计字符被存入变量i,后续遍历字符串的循环又复用i作为临时迭代变量,直接覆盖了用户输入的待统计字符值
  • 无匹配判断逻辑:遍历过程中没有校验当前字符是否等于待统计字符,只是无脑累加计数,最终输出的其实是原字符串的总长度,和你示例里输出6的现象完全吻合

修正后代码

s = input('Enter a string: ')

if s == '': 
    print('Empty String, please enter a string: ')
else:
    d = int(input('Please enter the character to be removed: '))
    print('The new string is: ', s[:d] + s[d+1:])

# 修改变量名避免冲突
target_char = input('Enter a character: ')
count = 0

# 遍历用单独的临时变量,增加匹配判断
for char in s:
    if char == target_char:
        count = count + 1
print(count)

测试验证

输入示例参数:

  • 输入字符串:banana
  • 待移除下标:0
  • 待统计字符:a
    运行后输出统计结果为3,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:06:08