首页 python基础教程 Python字符串查找find()、索引index()和统计count()函数使用方法
pay pay
教程目录

Python字符串查找find()、索引index()和统计count()函数使用方法

日期: 二月 13, 2023, 5:16 a.m.
栏目: python基础教程
阅读: 1234
作者: Python自学网-村长

摘要: find()查找函数:从一个字符串中查找是否包含某个字符串。

一、字符串检测

1.find()查找函数:从一个字符串中查找是否包含某个字符串。

先看看构造函数

def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
    """
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.
    """
    return 0

从上面的构造函数可以看出来除了传递索要查找的字符串,还可以指定查找位置。

website = 'http://www.wakey.com.cn/'
print(website.find('key'))  # 查找website中是否包含字符串'key'
print(website.find('key', 5, 10))  # 在第六和第14个字符之间查找,找不到返回-1
print(website.find('key', 5, 17))  # 在在第六和第17个字符之间查找

返回结果是:

13
-1
13

2.字符串索引index()

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

website = 'http://www.wakey.com.cn/'
# print(website.find('key'))  # 查找website中是否包含字符串'key'
# print(website.find('key', 5, 10))  # 在第六和第14个字符之间查找,找不到返回-1
# print(website.find('key', 5, 17))  # 在在第六和第17个字符之间查找

print(website.index('key', 5, 17))
print(website.index('key', 5, 10))

返回结果:13

Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/python知识总结/python基础/7-3.字符串检测和统计函数.py", line 9, in <module>
    print(website.index('key', 5, 10))
ValueError: substring not found

3.startwith()endwith()

这两个函数分别永凯检测一个字符串是以什么字符开头和结尾的,返回值是bool类型。

web = 'wakey.com.cn'
print(web.startswith('w'))
print(web.endswith('n'))
print(web.startswith('a'))
print(web.endswith('a'))

返回结果如下:

True
True
False
False

二、统计函数count()

count 方法用于检索指定字符串或字符在另一字符串中出现的次数,如果检索的字符串不存在,则返回 0,否则返回出现的次数。

web = 'wakey.com.cn'
print(web.count('.'))
print(web.count('a'))
print(web.count('5'))
print(web.count('.', 7))  # 从第八个字符查找字符串中有几个点

返回结果:

2
1
0
1

部分文字内容为【Python自学网】原创作品,转载请注明出处!视频内容已申请版权,切勿转载!
回顶部