掌握的 30 个必备 Python 字符串方法

图片[1]-掌握的 30 个必备 Python 字符串方法-山海云端论坛

简介:

Python 中的字符串是基本的数据类型,在几乎每个 Python 程序中都会使用到。本文将介绍 30 个最重要的内置字符串方法,希望读者能够从中找到对自己有帮助的技巧。

1. Slicing(切片)

切片操作是从列表或元组中取出部分元素的方法,可以按照一定条件(如特定范围、索引、分割值)进行切片操作。

<code>s = ' hello ' s = s[:] print(s) # hello s = ' hello ' s = s[3:8] print(s) # hello</code>

2. strip()

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

<code>s = ' hello '.strip() print(s) # hello s = '###hello###'.strip('#') print(s) # hello</code>

3. lstrip()

lstrip() 方法用于移除字符串左侧指定的字符(默认为空格或换行符)或字符序列。

<code>s = ' hello '.lstrip() print(s) # hello</code>

4. rstrip()

rstrip() 方法用于移除字符串右侧指定的字符(默认为空格或换行符)或字符序列。

<code>s = ' hello '.rstrip() print(s) # hello</code>

5. removeprefix()

Python 3.9 中移除前缀的函数。

<code>s = 'Arthur: three!'.removeprefix('Arthur: ') print(s) # three!</code>

6. removesuffix()

Python 3.9 中移除后缀的函数。

<code>s = 'HelloPython'.removesuffix('Python') print(s) # Hello</code>

7. replace()

将字符串中的指定内容替换成新的内容。

<code>s = 'string methods in python'.replace(' ', '-') print(s) # string-methods-in-python</code>

8. re.sub()

re 是正则表达式,sub 是 substitute 的缩写,表示替换。re.sub() 是相对复杂的替换方法,支持使用正则表达式进行替换操作。

<code>import re s = "string methods in python" s2 = re.sub("\s+", "-", s) print(s2) # string-methods-in-python</code>

9. split()

对字符串进行分割处理,返回一个包含分割结果的列表。

<code>s = 'string methods in python'.split() print(s) # ['string', 'methods', 'in', 'python']</code>

10. rsplit()

从右侧开始对字符串进行分割。

<code>s = 'string methods in python'.rsplit(' ', maxsplit=1) print(s) # ['string methods in', 'python']</code>

11. join()

以指定的字符串作为分隔符,将序列中的所有字符串连接成一个新的字符串。

<code>list_of_strings = ['string', 'methods', 'in', 'python'] s = '-'.join(list_of_strings) print(s) # string-methods-in-python</code>

12. upper()

upper() 方法用于将字符串中的所有字母转换为大写。

<code>s = 'simple is better than complex'.upper() print(s) # SIMPLE IS BETTER THAN COMPLEX</code>

13. lower()

lower() 方法用于将字符串中的所有字母转换为小写。

<code>s = 'SIMPLE IS BETTER THAN COMPLEX'.lower() print(s) # simple is better than complex</code>

14. capitalize()

capitalize() 方法用于将字符串的第一个字符转换为大写,其他字符转换为小写。

<code>s = 'simple is better than complex'.capitalize() print(s) # Simple is better than complex</code>

15. islower()

islower() 方法用于检查字符串中的所有字母是否都为小写,如果是则返回 True,否则返回 False。

<code>print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False print('simple is better than complex'.islower()) # True</code>

16. isupper()

isupper() 方法用于检查字符串中的所有字母是否都为大写,如果是则返回 True,否则返回 False。

<code>print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True print('SIMPLE IS BETTER THAN complex'.isupper()) # False</code>

17. isalpha()

isalpha() 方法用于检查字符串是否只包含字母,并且至少有一个字符。

<code>s = 'python' print(s.isalpha()) # True s = '123' print(s.isalpha()) # False s = 'python123' print(s.isalpha()) # False s = 'python-123' print(s.isalpha()) # False</code>

18. isnumeric()

isnumeric() 方法用于检测字符串中是否只包含数字字符。

<code>s = '123' print(s.isnumeric()) # True s = 'python123' print(s.isnumeric()) # False s = 'python-123' print(s.isnumeric()) # False</code>

19. isalnum()

isalnum() 方法用于检查字符串是否只包含字母或数字,并且至少有一个字符。

<code>s = 'python' print(s.isalnum()) # True s = '123' print(s.isalnum()) # True s = 'python123' print(s.isalnum()) # True s = 'python-123' print(s.isalnum()) # False</code>

20. count()

count() 方法用于返回指定内容在字符串中出现的次数。

<code>n = 'hello world'.count('o') print(n) # 2 n = 'hello world'.count('oo') print(n) # 0</code>

21. find()

find() 方法用于检测字符串中是否包含子字符串,如果找到返回开始的索引值,否则返回 -1。

<code>s = 'Machine Learning' idx = s.find('a') print(idx) # 1 print(s[idx:]) # achine Learning s = 'Machine Learning' idx = s.find('aa') print(idx) # -1 print(s[idx:]) # g s = 'Machine Learning' idx = s.find('a', 2) print(idx) # 10 print(s[idx:]) # arning</code>

22. rfind()

rfind() 方法用于返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。

<code>s = 'Machine Learning' idx = s.rfind('a') print(idx) # 10 print(s[idx:]) # arning</code>

23. startswith()

startswith() 方法用于检查字符串是否是以指定内容开头,是则返回 True,否则返回 False。

<code>print('Patrick'.startswith('P')) # True</code>

24. endswith()

endswith() 方法用于检查字符串是否是以指定内容结束,是则返回 True,否则返回 False。

<code>print('Patrick'.endswith('ck')) # True</code>

25. partition()

partition() 方法类似于 split(),但只会分割一次。

<code>s = 'Python is awesome!' parts = s.partition('is') print(parts) # ('Python ', 'is', ' awesome!') s = 'Python is awesome!' parts = s.partition('was') print(parts) # ('Python is awesome!', '', '')</code>

26. center()

center() 方法返回一个原字符串居中,并使用指定字符(默认为空格)填充至指定长度的新字符串。

<code>s = 'Python is awesome!' s = s.center(30, '-') print(s) # ------Python is awesome!------</code>

27. ljust()

ljust() 方法返回一个原字符串左对齐,并使用指定字符(默认为空格)填充至指定长度的新字符串。

<code>s = 'Python is awesome!' s = s.ljust(30, '-') print(s) # Python is awesome!------------</code>

28. rjust()

rjust() 方法返回一个原字符串右对齐,并使用指定字符(默认为空格)填充至指定长度的新字符串。

<code>s = 'Python is awesome!' s = s.rjust(30, '-') print(s) # ------------Python is awesome!</code>

29. f-Strings

f-string 是格式化字符串的新语法,它提供了一种简洁、可读性强的字符串格式化方式。

<code>num = 1 language = 'Python' s = f'{language} is the number {num} in programming!' print(s) # Python is the number 1 in programming!</code>

30. swapcase()

swapcase() 方法用于对字符串的大小写字母进行转换。

<code>s = 'HELLO world' s = s.swapcase() print(s) # hello WORLD</code>

通过掌握这些字符串方法,你可以更灵活地处理字符串,让你的 Python 编程变得更加高效和便捷。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容