即使对于 print() 超出 continue 块的某些行,也没有打印出任何内容

nothing printed out even for some lines where print() is out of continue block

我有一个文件 ~/practice/search_from 如下所示:

From i
ssdfadfksjaflkf
asdfasf
adf
sd
fd
fs
sgdggggggggggggsd
gsg
sdg
From j
dasdfewf
sdfas
adsf

我想打印以 From 开头的行。

所以我在 python 提示中做了以下操作:

>>> fhandle=open('practice/search_from')
>>> for line in fhandle:
...    if not line.startswith('From '):
...     continue
...    else:
...     print(line.rstrip())
... 
From i
From j

这段代码似乎工作正常。

然而,当我把

>>> fhandle=open('practice/search_from')
>>> for line in fhandle:
...     line = line.rstrip()
...     if not line.startswith('From:') :
...         continue
...     print(line)
... 

>>> fhandle=open('practice/search_from')
>>> for line in fhandle:
...     line = line.rstrip()
...     if not line.startswith('From:') :
...         continue
...     else:
...         print(line)

没有打印出来。为什么会这样?有没有办法修复最后两个代码?

非常感谢。

没有任何内容打印出来,因为您的文件中没有任何行以 From: 开头。

只有当该行以 "From:"(包括冒号)开头时,

line.startswith('From:') 才会是 True。因此 not line.startswith('From:') 在您的文件中将始终为 True(没有以 From: 开头的行),并且您将始终评估 continue 行,该行跳转到下一次迭代for 循环。

您的代码很好,除了您正在使用 From: 进行搜索。

从您的代码中删除 colon(:),它将正常工作:

In [2296]: fhandle=open('practice/search_from')

In [2297]: for line in fhandle:
      ...:     line = line.rstrip()
      ...:     if not line.startswith('From'):
      ...:         continue
      ...:     print(line)
      ...:     
From i
From j