python - 使用 for 循环获取行数

标签 python for-loop if-statement

我需要一个函数来查找所有以“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'.

最佳答案

这是一个错误的缩进:

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.

关于python - 使用 for 循环获取行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57644149/

相关文章:

python - 比较两个数据框,但仅在特定列上比较

python 停止 selenium 独立服务器

Python .drop 没有给出我期望的结果

javascript - 使用 JavaScript 返回正确的行号,而不使用内联代码

python - 如何在迭代列表时迭代其键时更改字典

sql - MySQL 计算字段中的 IF 条件

python - 如何修复此 python 错误?溢出错误 : cannot convert float infinity to integer

r - 在R中以增量循环

javascript - 如果背景等于问题

if-statement - Posix 标准中的条件