欢迎访问宙启技术站
智能推送

Python中字符串处理的函数大全:capitalize,replace,count

发布时间:2023-05-31 18:59:00

Python中字符串处理的函数非常丰富,可以方便地实现对字符串的操作。下面列举了一些常用的字符串处理函数,并对其进行简要介绍。

1. capitalize:将字符串的 个字母大写

例如,对于字符串s="hello world",使用s.capitalize()会得到"Hello world"。

2. upper:将字符串全部都变成大写字母

例如,对于字符串s="hello world",使用s.upper()会得到"HELLO WORLD"。

3. lower:将字符串全部都变成小写字母

例如,对于字符串s="HELLO WORLD",使用s.lower()会得到"hello world"。

4. title:将每个单词的首字母大写

例如,对于字符串s="hello world",使用s.title()会得到"Hello World"。

5. swapcase:将字符串中的大写字母变为小写,小写字母变为大写

例如,对于字符串s="HeLlO WoRlD",使用s.swapcase()会得到"hElLo wOrLd"。

6. replace:将字符串中的某个字符或子串替换为另一个字符或子串

例如,对于字符串s="hello world",使用s.replace("o", "0")会得到"hell0 w0rld"。

7. strip:去掉字符串两端的空格

例如,对于字符串s="   hello world   ",使用s.strip()会得到"hello world"。

8. lstrip:去掉字符串左端的空格

例如,对于字符串s="   hello world   ",使用s.lstrip()会得到"hello world   "。

9. rstrip:去掉字符串右端的空格

例如,对于字符串s="   hello world   ",使用s.rstrip()会得到"   hello world"。

10. join:将列表中的元素合并为一个字符串,中间用指定的分隔符隔开

例如,对于列表l=["hello", "world"],使用" ".join(l)会得到"hello world"。

11. split:将字符串按照指定的分隔符分解为列表

例如,对于字符串s="hello world",使用s.split(" ")会得到["hello", "world"]。

12. partition:将字符串按照指定的分隔符分解为三个元素的元组,中间是分隔符

例如,对于字符串s="hello world",使用s.partition(" ")会得到("hello", " ", "world")。

13. rpartition:将字符串按照指定的分隔符分解为三个元素的元组,从右往左数,中间是分隔符

例如,对于字符串s="hello world",使用s.rpartition(" ")会得到("hello", " ", "world")。

14. center:让字符串居中,两边用指定字符填充

例如,对于字符串s="hello",使用s.center(10, "*")会得到"***hello***"。

15. ljust:让字符串左对齐,右边用指定字符填充

例如,对于字符串s="hello",使用s.ljust(10, "*")会得到"hello*****"。

16. rjust:让字符串右对齐,左边用指定字符填充

例如,对于字符串s="hello",使用s.rjust(10, "*")会得到"*****hello"。

17. count:计算子串在字符串中出现的次数

例如,对于字符串s="hello world",使用s.count("l")会得到3。

18. find:查找子串在字符串中的位置,从左往右

例如,对于字符串s="hello world",使用s.find("l")会得到2。

19. rfind:查找子串在字符串中的位置,从右往左

例如,对于字符串s="hello world",使用s.rfind("l")会得到9。

20. index:查找子串在字符串中的位置,从左往右,不存在则报错

例如,对于字符串s="hello world",使用s.index("l")会得到2。

21. rindex:查找子串在字符串中的位置,从右往左,不存在则报错

例如,对于字符串s="hello world",使用s.rindex("l")会得到9。

22. startswith:判断字符串是否以指定的子串开头

例如,对于字符串s="hello world",使用s.startswith("h")会得到True。

23. endswith:判断字符串是否以指定的子串结尾

例如,对于字符串s="hello world",使用s.endswith("d")会得到True。

总结:Python中的字符串处理函数非常丰富,可以方便地实现对字符串的操作。这些函数常用于数据处理和字符串处理任务中。掌握这些函数能够让Python编程更加高效和易于维护。