常用的python字符串方法有哪一些?
导读:这篇文章给大家分享的是常用的python字符串方法。小编觉得挺实用的,因此分享给大家做个参考,文中示例代码介绍的非常详细,感兴趣的朋友接下来一起跟随小编看看吧。 1、find(sub[, start[, end]] 在索引start和...
这篇文章给大家分享的是常用的python字符串方法。小编觉得挺实用的,因此分享给大家做个参考,文中示例代码介绍的非常详细,感兴趣的朋友接下来一起跟随小编看看吧。
1、find(sub[, start[, end]])
在索引start
和end
之间查找字符串sub
找到,则返回最左端的索引值,未找到,则返回-1
start
和end
都可省略,省略start
说明从字符串开头找
省略end
说明查找到字符串结尾,全部省略则查找全部字符串
source_str = "There is a string accessing example" print(source_str.find('r')) > > > 3
2、count(sub, start, end)
返回字符串sub
在start
和end
之间出现的次数
source_str = "There is a string accessing example" print(source_str.count('e')) > > > 5
3、replace(old, new, count)
old
代表需要替换的字符,new
代表将要替代的字符,count
代表替换的次数(省略则表示全部替换)
source_str = "There is a string accessing example" print(source_str.replace('i', 'I', 1)) > > > There Is a string accessing example # 把小写的i替换成了大写的I
4、split(sep, maxsplit)
以sep
为分隔符切片,如果maxsplit
有指定值,则仅分割maxsplit
个字符串
分割后原来的str类型将转换成list
类型
source_str = "There is a string accessing example" print(source_str.split(' ', 3)) > > > ['There', 'is', 'a', 'string accessing example'] # 这里指定maxsplit=3,代表只分割前3个
5、startswith(prefix, start, end)
判断字符串是否是以prefix
开头,start
和end
代表从哪个下标开始,哪个下标结束
source_str = "There is a string accessing example" print(source_str.startswith('There', 0, 9)) > > > True
6、endswith(suffix, start, end)
判断字符串是否以suffix
结束,如果是返回True
,否则返回False
source_str = "There is a string accessing example" print(source_str.endswith('example')) > > > True
7、lower
将所有大写字符转换成小写
8、upper
将所有小写字符转换成大写
9、join
将列表拼接成字符串
list1 = ['ab', 'cd', 'ef'] print(" ".join(list1)) > > > ab cd ef
10、切片反转
list2 = "hello" print(list2[::-1]) > > > olleh
以上就是关于常用的python字符串方法的介绍啦,上述示例具有一定的借鉴价值,有需要的朋友可以参考学习,希望对大家学习python有帮助,想要了解更多可以继续浏览网络其他相关的文章。
文本转载自脚本之家
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 常用的python字符串方法有哪一些?
本文地址: https://pptw.com/jishu/651526.html