【100+ python基础入门 您所在的位置:网站首页 字符计算函数 【100+ python基础入门

【100+ python基础入门

2023-01-14 11:28| 来源: 网络整理| 查看: 265

一、字符串检测

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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有