python查找计算函数的整理

1、len计算字符串的字符数量。

一个汉字或一个字母算一个字符。

name='我是aa\n'#\n作为换行符,算一个字符
num=len(name)
print(num)
输出:5

2、find检索子串的索引/下标位置,从0开始检索相应的索引。

找不到时返回-1。

#a.find()#从0开始找对应索引;如果有多个,则找从左数的第一个
msg='Thedayisasunnyday'
result1=msg.find('d')
print(result1)
result2=msg.find('d',5,-1)#从第五个索引开始到最后一个索引之间,'d'出现的第一个索引
print(result2)
result3=msg.find('d',5,9)#从第五个索引开始到第九个索引之间(包含5不包含9),'d'出现的第一个索引
print(result3)

输出:
4
19
-1

3、rfind功能与find相同,不同之处在于从右边开始寻找相应的索引。

#a.rfind()#从右边开始找对应索引
msg='Thedayisasunnyday'
result1=msg.rfind('d')
result2=msg.rfind('da')#找多个字符,会返回找到的'd'的索引
print(result1)
print(result2)

输出:
19
19
4、index/rindex返回所需值的索引。
msg='Thedayisasunnyday'
result=msg.index('dd')
print(result)

输出:
Traceback(mostrecentcalllast):
File"xxx.py",line43,in<module>
result=msg.index('dd')
ValueError:substringnotfound

以上就是python查找计算函数的整理,希望对大家有所帮助。更多Python学习指路:Python基础教程

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。