首页 > 解决方案 > 使用 for 循环获取行数

问题描述

我需要一个函数来查找所有以“end”结尾的行。然后,我需要计算总共有多少行并使用 print 打印出数字。

这是我下面的代码:

count = 0

for line in open("jane_eyre.txt"):
    line_strip = line.rstrip()
    if line_strip.endswith(" end"):    
        lines = line_strip
        count += 1
        print("There are", count, "lines that end in 'end'.")  

预期结果:

There are 4 lines that end in 'end'.

我目前的结果:

There are 1 lines that end in 'end'.
There are 2 lines that end in 'end'.
There are 3 lines that end in 'end'.
There are 4 lines that end in 'end'.

标签: pythonfor-loopif-statement

解决方案


It's a miss-indentation:

count = 0

for line in open("jane_eyre.txt"):
    line_strip = line.rstrip()
    if line_strip.endswith(" end"):    
        lines = line_strip
        count += 1
print("There are", count, "lines that end in 'end'.") # < look at now and before and compare.

推荐阅读