Python中IF语句的求值
请帮助我尝试理解此脚本的评估。这一定是我不明白的简单事情。我想扫描一个文本文件并输出具有特定字符串值的行 例如,我的txt文件将包含简单的内容:Python中IF语句的求值,python,python-3.x,Python,Python 3.x,请帮助我尝试理解此脚本的评估。这一定是我不明白的简单事情。我想扫描一个文本文件并输出具有特定字符串值的行 例如,我的txt文件将包含简单的内容: beep boop bop Hey beep boop bop 脚本正在寻找带有“Hey”的行并试图输出该行 file_path = "C:\\downloads\\test.txt" i = 0 file_in = open(file_path,"r+") # read & write for lines in file_in.rea
beep
boop
bop
Hey
beep
boop
bop
脚本正在寻找带有“Hey”的行并试图输出该行
file_path = "C:\\downloads\\test.txt"
i = 0
file_in = open(file_path,"r+") # read & write
for lines in file_in.readlines():
i+=1
#if lines.rfind("this entity will be skipped..."):
if lines.find("Hey"):
print(i, lines)
file_in.close()
出于某种原因,它会输出每一行,但找到匹配的那一行除外。这怎么可能呢?如果在行中“嘿”,那么执行
可能比在行中执行更简单:
,而不是在行中执行。查找(“嘿”):
。如果您真的想使用find()
,您可以这样做:If lines.find(“Hey”)!=-1:
虽然丹尼尔的答案当然是正确的,应该被接受,但我想为我的强迫症火上浇油,并提供一些改进:
# use context managers to automatically release file handler
with open(file_path) as file_in:
# file objects are iterable, will return lines
# reading entire file in memory can crash if file is too big
# enumerate() is a more readable alternative to manual counters
for i, line in enumerate(file_in): # 'line' should be singular
if "Hey" in line: # same as Daniel
print(i, line)
.find(sub)
返回一个整数——如果找到sub
,则返回sub
的第一个索引,如果未找到,则返回-1
当出现“Hey”时,它位于第一个索引(0)处,因此.find()
返回的就是这个索引。否则,找不到“Hey”,因此.find()
返回-1
由于python将除0以外的所有整数都视为True,因此当返回0时,即当找到“Hey”时,该条件的计算结果为True
将.find()的用法更改为能够以您想要的方式实现if语句的用法。试试这个if!行。查找(“嘿”):
不要尝试。尝试阅读find
方法的文档:“返回找到子字符串sub的S中的最低索引…失败时返回-1”。这意味着如果它位于字符串的开头,find
返回0
。所以您需要if line.find(…)>=0
。