脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python字符串常用方法解析

python字符串常用方法解析

2022-02-18 00:25Silent丿丶黑羽 Python

这篇文章主要介绍了python字符串常用方法,find、count、replace、split、startswith、endswith等多种方法,需要的朋友可以参考一下文章得具体内容,希望对你有所帮助

1、find(sub[, start[, end]])

在索引startend之间查找字符串sub
​找到,则返回最左端的索引值,未找到,则返回-1
startend都可省略,省略start说明从字符串开头找
省略end说明查找到字符串结尾,全部省略则查找全部字符串

?
1
2
3
4
source_str = "There is a string accessing example"
print(source_str.find('r'))
>>> 3

2、count(sub, start, end)

返回字符串substartend之间出现的次数

?
1
2
3
4
source_str = "There is a string accessing example"
print(source_str.count('e'))
>>> 5

3、replace(old, new, count)

old代表需要替换的字符,new代表将要替代的字符,count代表替换的次数(省略则表示全部替换)

?
1
2
3
4
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类型

?
1
2
3
4
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开头,startend代表从哪个下标开始,哪个下标结束

?
1
2
3
4
source_str = "There is a string accessing example"
print(source_str.startswith('There', 0, 9))
>>> True

6、endswith(suffix, start, end)

判断字符串是否以suffix结束,如果是返回True,否则返回False

?
1
2
3
4
source_str = "There is a string accessing example"
print(source_str.endswith('example'))
>>> True

7、lower

将所有大写字符转换成小写

8、upper

将所有小写字符转换成大写 

9、join

将列表拼接成字符串

?
1
2
3
4
list1 = ['ab', 'cd', 'ef']
print(" ".join(list1))
>>> ab cd ef

10、切片反转

?
1
2
3
list2 = "hello"
print(list2[::-1])
>>> olleh

到此这篇关于python字符串常用方法的文章就介绍到这了,更多相关python字符串内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/jiakecong/p/14438571.html

延伸 · 阅读

精彩推荐