我需要在文件中只使用find()命令编写一个Python程序来打印所有那些拥有Python的行 [英] I need to write a Python program using only find() command in files to print all those line which has Python
问题描述
我需要在文件中使用find()命令打印出现python的所有行。使用python。
I need do to print all that lines in which python appears using find() command in a file. Using python.
fhand=open('demo.txt')
for line in fhand:
line=line.rstrip()
if(line.find('python')):
continue
print(line)
这些是我的文件内容
these are my file content
python is fun
python java
sai python
sachin
ganesha
目前仅打印前2行
我尝试了什么:
currently its printing first 2 lines only
What I have tried:
fhand=open('demo.txt')
for line in fhand:
line=line.rstrip()
if(line.find('python')):
continue
print(line)
这是我的代码,请帮帮我
this is my code please help me
推荐答案
fhand=open('demo.txt')
for line in fhand:
line=line.rstrip()
if( line.find('python') != -1):
print(line)
find
方法将索引返回到第一次出现的查找目标。您只打印索引为零的那些。将您的循环更改为:
Thefind
method returns the index to the first occurrence of the find target. You are only printing the ones where the index is zero. Change your loop to:
for line in fhand:
line=line.rstrip()
if(line.find('python') != -1):
print(line)
将来请在< pre lang =之间正确格式化代码蟒>< /预>标签,正如我在这里所做的那样。它使它更具可读性。
In future please format your code properly between <pre lang="Python"></pre> tags, as I have done here. It makes it more readable.
if(line.find('python')):
continue
Python String find()方法 [ ^ ]
根据文档 find()
为'找不到'返回-1,为'找到'返回索引(0)...但是'if'是关于ture / false,其中除0以外的任何数字是真的......
Python String find() Method[^]
According to the documentation find()
returns -1 for 'not-found' and index (0 based) for 'found'... However 'if' is about ture/false, where any number except 0 is true...
这篇关于我需要在文件中只使用find()命令编写一个Python程序来打印所有那些拥有Python的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!