【100+ python基础入门-16】字符串检测和统计函数

导读:本篇文章讲解 【100+ python基础入门-16】字符串检测和统计函数,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

一、字符串检测

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基础视频学习,祝大家学有所成。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/73457.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!