【问题标题】:nothing printed out even for some lines where print() is out of continue block即使对于 print() 超出 continue 块的某些行,也没有打印任何内容
【发布时间】:2018-12-11 07:06:01
【问题描述】:

我有一个文件~/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)

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

非常感谢。

【问题讨论】:

    标签: python python-3.x continue


    【解决方案1】:

    您的代码很好,除了您使用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
    

    【讨论】:

    • 非常感谢!我能再问你一个问题吗?在执行 fhandle: 循环中的第一行 for 后,如果我再次执行相同的 for 循环,它不会打印任何内容。我必须在每个循环之前打开它吗?非常感谢@Mayank
    • 是的,您需要再次打开 fhandle。
    • 我明白了。非常感谢!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 2020-05-18
      • 2021-10-16
      • 2018-06-05
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多