gpt4 book ai didi

python - 使用 for 循环获取行数

转载 作者:行者123 更新时间:2023-12-01 00:37:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com