Fork me on GitHub

Python index() 方法

描述

Python index() 方法从字符串中找出某个子字符串第一个匹配项的索引位置,该方法与 find() 方法一样,只不过如果子字符串不在字符串中会报一个异常。

语法

index() 方法语法:

S.index(sub[,start=0[,end=len(S)]])

参数

  • sub -- 指定检索的子字符串
  • S -- 父字符串
  • start-- 可选参数,开始索引,默认为0。(可单独指定)
  • end-- 可选参数,结束索引,默认为字符串的长度。(不能单独指定)

返回值

返回子字符串第一个匹配项出现在字符串中的索引位置,如果没有匹配项则会报一个异常

实例

以下实例展示了 index() 方法的实例:

#!/usr/bin/python3

S1 = "Runoob example....wow!!!"
S2 = "exam";

print (S1.index(S2))
print (S1.index(S2, 5))
print (S1.index(S2, 10))

以上实例输出结果如下(未发现的会出现异常信息):

7
7
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (str1.index(str2, 10))
ValueError: substring not found
posted @ 2017-10-18 14:56  IT技术随笔  阅读(8173)  评论(0编辑  收藏  举报
返回顶部↑