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