本文共 1050 字,大约阅读时间需要 3 分钟。
本文介绍python字符串内建函数str.index( )和str.rindex( )的使用。
1》首先,通过help( str.index)函数获取帮助:
>>> help(str.index)
Help on method_descriptor: index(...) S.index(sub [,start [,end]]) -> intLike S.find() but raise ValueError when the substring is not found.
str.index( )函数的使用,举例如下:
>>> s='love python!'
>>> s.index('ove') # 默认的查找区间是 [0,len(s)) 1 >>> s.index('ove',2) # 只给出了查找起点是2,则对应的查找区间是 [2,len(s)) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found >>> s.index('ove',1) # 只给出了查找起点是1,则对应的查找区间是 [1,len(s)) 1 >>> s.index('ove',1,4) # 指定查找区间是 [1,4) 1 >>> s.index('ove',1,3) # 指定查找区间是 [1,3) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found2》通过help(str.rindex)获取帮助信息:
>>> help(str.rindex)
Help on method_descriptor: rindex(...) S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found.>>> s='love python love python!'
>>> s.index('python') #返回左边第一个子串'python'的下标 5 >>> s.rindex('python')#返回右边第一个子串'python'的下标 17(完)
转载地址:http://wdyai.baihongyu.com/