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

一、字符串检测

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王子玉博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值