本文共 1331 字,大约阅读时间需要 4 分钟。
find函数用于检测字符串中是否包含子字符串sub,如果包含子字符串则返回开始索引值,否则返回-1
语法格式如下:str.find(sub[ , start[ , end]])
参数如下:
sub:指定检索的字符串
start:开始索引,默认为0
end:结束索引,默认为字符串的长度
mystr='hello world iteima and itheimaApp'index=mystr.find('world')print(index)
mystr='hello world iteima and itheimaApp'index=mystr.find('world',0,15)print(index)
index函数用于检测字符串中是否包含子字符串sub,如果包含子字符串则返回开始索引值,否则报错
语法格式如下:str.index(sub[ , start[ , end]])
参数如下:
sub:指定检索的字符串
start:开始索引,默认为0
end:结束索引,默认为字符串的长度
mystr='hello world iteima and itheimaApp'index=mystr.index('itema',0,15)print(index)
字符串itema不在0到15的范围内,系统报错
count函数用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始于结束位置,该方法返回子字符在字符串中出现的次数。
语法格式如下:
str.count(sub[, start [, end]])
参数如下:
sub:搜索的子字符串
start:字符串开始搜索的位置,默认为第一个字符,该字符索引值为0
end:字符串结束搜索的位置,默认为字符的长度
mystr='hello world iteima and itheimaApp'result=mystr.count('iteima')print(result)
mystr='hello world iteima and iteimaApp'result=mystr.count("iteima")print(result)
replace函数把字符串中的old字符替换成新的new字符,方法返回的字符串中old字符替换成new的字符后生成的新的字符串,
如果指定第三个参数count,则替换不超过count次
语法格式:
str.replace(old,new[,count])
old:将被替换的子字符串
new:新字符串,用于替换old子字符串
count:可选字符串,替换不超过count次
mystr='hello world iteima and iteimaApp'newstr=mystr.replace('iteima','chuancy',1)print(newstr)
如果未指定count,则全部替换
mystr='hello world iteima and iteimaApp'newstr=mystr.replace('iteima','chuancy')print(newstr)