Python3 index()方法

Python 3 教程 · 2019-02-05 21:12:25

描述

index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

语法

index()方法语法:

str.index(str, beg=0, end=len(string))

参数

  • str -- 指定检索的字符串
  • beg -- 开始索引,默认为0。
  • end -- 结束索引,默认为字符串的长度。

返回值

如果包含子字符串返回开始的索引值,否则抛出异常。

实例

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

#!/usr/bin/python3

str1 = "Codercto example....wow!!!"
str2 = "exam";

print (str1.index(str2))
print (str1.index(str2, 5))
print (str1.index(str2, 10))

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

7
7
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (str1.index(str2, 10))
ValueError: substring not found

注意:在接下来的几个章节中,我们会详细介绍Python Exception的使用。

点击查看所有 Python 3 教程 文章: https://codercto.com/courses/l/10.html

查看所有标签

The Linux Programming Interface

The Linux Programming Interface

Michael Kerrisk / No Starch Press / 2010-11-6 / GBP 79.99

The Linux Programming Interface describes the Linux API (application programming interface)-the system calls, library functions, and other low-level interfaces that are used, directly or indirectly, b......一起来看看 《The Linux Programming Interface》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具