python 字符串查找有4个方法:find()、index()、rfind()、rindex()。
rfind和rindex方法用法和上面一样,只是从字符串的末尾开始查找。
#-*- coding:utf-8 -*-
if __name__ == "__main__":
str = "abcd1234abcd1234"
pos1 = str.find('d')
print "pos1={0}".format(pos1)
pos2 = str.find('5')
print "pos2={0}".format(pos2)
pos3 = str.rfind('d')
print "pos3={0}".format(pos3)
pos4 = str.index('d')
print "pos4=%d"%(pos4)
try:
pos5 = str.index('5')
print "pos4=%d"%(pos5)
except Exception as e:
print "Error:",e
pos6 = str.rindex('d')
输出结果:
pos1=3
pos2=-1
pos3=11
pos4=3
Error: substring not found
pos6=11