博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python字符串操作
阅读量:4100 次
发布时间:2019-05-25

本文共 1331 字,大约阅读时间需要 4 分钟。

find函数

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函数

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函数

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函数

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)

你可能感兴趣的文章
通过mavlink实现自主航线的过程笔记
查看>>
Flutter Boost的router管理
查看>>
Vue2.0全家桶仿腾讯课堂(移动端)
查看>>
React+Redux系列教程
查看>>
19 个 JavaScript 常用的简写技术
查看>>
iOS开发支付集成之微信支付
查看>>
React非嵌套组件通信
查看>>
浏览器兼容性问题解决方案 · 总结
查看>>
一个很棒的Flutter学习资源列表
查看>>
为什么你应该放弃React老的Context API用新的Context API
查看>>
Koa2初体验
查看>>
Koa 2 初体验(二)
查看>>
Koa2框架原理解析和实现
查看>>
C++模板
查看>>
【C#】如何实现一个迭代器
查看>>
【C#】利用Conditional属性完成编译忽略
查看>>
【Unity】微信登录后将头像存为bytes,将bytes读取成sprite图片
查看>>
【Unity】使用GPS定位经纬度
查看>>
最小费用流 Bellman-Ford与Dijkstra 模板
查看>>
mapReduce(3)---入门示例WordCount
查看>>