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

 1 def extract_from_tag(tag,line):
 2     opener = "<" + tag + ">"
 3     closer = "</" + tag + ">"
 4     try:
 5         i = line.index(opener)# i = 7
 6         start = i + len(opener) # start = 7 + 5 =12
 7         j = line.index(closer,start) #j =16
 8         return line[start:j] # retrun line[12:16]
 9     except ValueError:
10         return None
11 a = extract_from_tag("red","what a <red>reosedf</red> this is")
12 print(a)
13 print(len(a))
str.index()
 1 def extract_from_tag(tag,line):
 2     opener = "<" + tag + ">"
 3     closer = "</" + tag + ">"
 4     i = line.find(opener) # i = 7
 5     if i != -1:
 6         start = i + len(opener) #start = 7+5=12
 7         j = line.find(closer,start) # j = 19
 8         if j !=-1:
 9             return line[start:j]  #line[12:19]
10     return None
11 a = extract_from_tag("red","what a <red>rose</red> this is")
12 print(a)
str.find()

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

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

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

每天更新一点点,温习一点点点,进步一点点
原文地址:https://www.cnblogs.com/lmgsanm/p/8331151.html