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

Python 3.6.5统计字母时遇TypeError: 'int' object is not iterable如何修复?

Fixing the TypeError: 'int' object is not iterable in Your Python Code

Hey there, let's break down what's going wrong and fix your code step by step.

The Root Cause of the Error

That TypeError: 'int' object is not iterable is coming from this line:

for i in h:

You set h = len(line) which gives you an integer (the length of the current line). But for loops need an iterable object (like a string, list, or tuple) to loop through—you can't loop over a single integer, hence the error.

On top of that, your character check was off: if line == "a" or line == "A" was comparing the entire line to a single character, which would never be true. You need to check each individual character instead.

Corrected Code

Here's the fixed version that will count all 'a' and 'A' characters correctly:

x = 0
f = open('in_a.txt', encoding='utf-8')
for line in f:
    # Loop through each character in the current line directly
    for char in line:
        if char == "a" or char == "A":
            x += 1
print("this document has %d A or a characters" % (x))

Key Changes Made

  • Removed h = len(line) and the invalid for i in h loop—instead, we iterate directly over the line string (strings are iterable, so we can loop through each character one by one)
  • Changed line to char in the condition check, so we're verifying each single character instead of the whole line
  • Tweaked "documents" to "document" for grammatical accuracy

When you run this with your test text, it will output exactly what you expect: this document has 10 A or a characters.

内容的提问来源于stack exchange,提问作者Crazy coding kid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:14:10