ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Python startswith()和endswith()方法及 index()方法:检测字符串中是否包含某子串

2026/9/24 21:52:11 拓冰建站 浏览量
Python startswith()和endswith()方法及 index()方法:检测字符串中是否包含某子串

Python startswith()和endswith()方法 

Python 字符串变量还可以使用 startswith() 和endswith() 方法。

startswith()方法

startswith() 方法用于检索字符串是否以指定字符串开头,如果是返回 True;反之返回 False。此方法的语法格式如下:

str.startswith(sub[,start[,end]])

此格式中各个参数的具体含义如下:

str:表示原字符串;

sub:要检索的子串;

start:指定检索开始的起始位置索引,如果不指定,则默认从头开始检索;

end:指定检索的结束位置索引,如果不指定,则默认一直检索在结束。

【例 1】判断“c.biancheng.net”是否以“c”子串开头。

>>> str = "c.biancheng.net"
>>> str.startswith("c")
True

【例 2】

>>> str = "c.biancheng.net"
>>> str.startswith("http")
False

【例 3】从指定位置开始检索。

>>> str = "c.biancheng.net"
>>> str.startswith("b",2)
True

endswith()方法

endswith() 方法用于检索字符串是否以指定字符串结尾,如果是则返回 True;反之则返回 False。该方法的语法格式如下:

str.endswith(sub[,start[,end]])

此格式中各参数的含义如下:

str:表示原字符串;

sub:表示要检索的字符串;

start:指定检索开始时的起始位置索引(字符串第一个字符对应的索引值为 0),如果不指定,默认从头开始检索。

end:指定检索的结束位置索引,如果不指定,默认一直检索到结束。

【例 4】检索“c.biancheng.net”是否以“net”结束。

>>> str = "c.biancheng.net"
>>> str.endswith("net")
True

 Python index()方法:检测字符串中是否包含某子串

同 find() 方法类似,index() 方法也可以用于检索是否包含指定的字符串,不同之处在于,当指定的字符串不存在时,index() 方法会抛出异常。

index() 方法的语法格式如下:

str.index(sub[,start[,end]])

此格式中各参数的含义分别是:

str:表示原字符串;

sub:表示要检索的子字符串;

start:表示检索开始的起始位置,如果不指定,默认从头开始检索;

end:表示检索的结束位置,如果不指定,默认一直检索到结尾。

【例 1】用 index() 方法检索“c.biancheng.net”中首次出现“.”的位置索引。

>>> str = "c.biancheng.net"
>>> str.index('.')
1

【例 2】当检索失败时,index()会抛出异常。

>>> str = "c.biancheng.net"
>>> str.index('z')
Traceback (most recent call last):File "<pyshell#49>", line 1, in <module>str.index('z')
ValueError: substring not found

同 find() 和 rfind() 一样,字符串变量还具有 rindex() 方法,其作用和 index() 方法类似,不同之处在于它是从右边开始检索,例如:

>>> str = "c.biancheng.net"
>>> str.rindex('.')
11