python - 使用 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'.
解决方案
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.
推荐阅读
- java - 类型转换器整数、浮点数、长整数的房间数据库问题
- r - 将项目数量合并到 Apriori 算法的事务中
- angular5 - 如何从`content`元素中解开html内容
- html - position:fixed navbar takes margin attribute of another div
- redhat-containers - A procedure to install minishift on Fedora?
- r - 将数据框的两个列向量转换为单个数值列
- mysql - Running 2 instances of mysql, one local 3306 and one for ampps?
- swift - 如何使用 UIView 在单选按钮上制作多行标题
- c# - RavenDb:IDocumentQuery 结果中的计算字段
- python - 返回最大日期时间值