str.index()与str.find()比较

时间:2023-03-10 02:45:21
str.index()与str.find()比较
 def extract_from_tag(tag,line):
opener = "<" + tag + ">"
closer = "</" + tag + ">"
try:
i = line.index(opener)# i = 7
start = i + len(opener) # start = 7 + 5 =12
j = line.index(closer,start) #j =16
return line[start:j] # retrun line[12:16]
except ValueError:
return None
a = extract_from_tag("red","what a <red>reosedf</red> this is")
print(a)
print(len(a))

str.index()

 def extract_from_tag(tag,line):
opener = "<" + tag + ">"
closer = "</" + tag + ">"
i = line.find(opener) # i = 7
if i != -1:
start = i + len(opener) #start = 7+5=12
j = line.find(closer,start) # j = 19
if j !=-1:
return line[start:j] #line[12:19]
return None
a = extract_from_tag("red","what a <red>rose</red> this is")
print(a)

str.find()

如果需要在某个字符串中找到另一个字符串所在的位置,有两种方法:

  1. 使用str.index()方法。该方法返回子字符串的索引位置,或者在失败时产生一个ValueError异常
  2. 使用str.find()方法。该方法返回子字符串的索引位置,或者在失败时返回-1

这两种方法都要把寻找的字符串作为第一个参数,还可以有两个可选的参数。其中第二个参数是待搜索的字符串的起始位置,第三个则是其终点位置