python字符串检索和统计函数的使用方法
2023-03-20 14:56:07 时间
一、字符串检测
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个字符之间查找,找不到返回-1print(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自学网查看关于这个知识点的相关python基础视频学习,祝大家学有所成。
相关文章
- Python中的函数与方法 以及Bound Method和Unbound Method
- 一文贯通python文件读取
- Python 中的异步编程:Asyncio
- 7个你现在就该学习Python的理由
- 提高Python运行效率的六个窍门
- Python数据科学:神经网络
- 一篇文章看懂大数据分析就业前景及职能定位
- R和Python中的文本挖掘:8个入门小贴士
- 告诉你为什么Python有点慢,但我却无所谓?
- 专注学习DevOps编程语言Top 5推荐
- Python发送邮件脚本
- Python多进程并行编程实践: mpi4py 的使用
- Python语言在未来的发展前景
- Python vs Ruby: 谁是最好的 web 开发语言?
- Python对Ruby:谁在Web开发领域更胜一筹?
- Python一行代码完成并行任务
- Python开发者2017应该关注的七个类库
- python爬虫入门基本知识
- 在终端中优雅地编写Python
- Python机器学习实战:信用卡欺诈检测