­

Python学习入门到精通:字符串方法

  • 2020 年 2 月 24 日
  • 筆記

字符串提供了很多内建方法,你必须掌握这些方法,否则,将无法娴熟的处理字符串。这些方法,暂时不需要你死记硬背,但至少你应该有一些印象,在处理字符串问题时,如果做不到信手拈来,可以查阅资料,寻访百度或是谷歌,下面这这些方法的列表

方法名称

功能描述

capitalize()

将字符串的第一个字符转换为大写

center

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格

count

返回子串出现的次数

encode

以 encoding 指定的编码格式编码字符串

endswith

检查字符串是否以 suffix 结束

find

查找子串sub在字符串中的位置,如果找不到返回-1

index

跟find()方法一样,只不过如果sub不在字符串中会报一个异常

isalnum

如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False

isalpha

如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False

isdigit

如果字符串只包含数字则返回 True 否则返回 False

islower

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False

isnumeric

如果字符串中只包含数字字符,则返回 True,否则返回 False

isspace()

如果字符串中只包含空白,则返回 True,否则返回 False.

istitle()

如果字符串是标题化的(见 title())则返回 True,否则返回 False

isupper()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False

join(seq)

以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串

len(string)

返回字符串长度

ljust(width[, fillchar])

返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。

lower()

转换字符串中所有大写字符为小写

lstrip()

截掉字符串左边的空格或指定字符

replace(old, new[, count])

将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 count 次

rfind(sub[, start[, end]])

类似于 find()函数,不过是从右边开始查找

rindex(sub[, start[, end]])

类似于 index(),不过是从右边开始

rjust(width[, fillchar])

返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串

rstrip()

删除字符串字符串末尾的空格

split(sep=None, maxsplit=-1)

以 sep为分隔符截取字符串,如果 maxsplit 有指定值,则仅截取 maxsplit+1 个子字符串

splitlines([keepends])

按照行('r', 'rn', n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

startswith(prefix[, start[, end]])

检查字符串是否是以指定子字符串 prefix 开头

strip([chars])

在字符串上执行 lstrip()和 rstrip()

swapcase()

将字符串中大写转换为小写,小写转换为大写

title()

返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())

upper()

转换字符串中的小写字母为大写

zfill (width)

返回长度为 width 的字符串,原字符串右对齐,前面填充0

isdecimal()

检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false

1. capitalize

将字符串的第一个字符转换为大写,这个功能对于我们中国的程序员来说没什么用处

word = 'hello'  print(word.capitalize())    # Hello  

2. center

方法定义

def center(self, width, fillchar=None):      pass  

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格

word = 'hello'  print(word.center(9, '*'))  # **hello**  

3. count

方法定义

def count(self, sub, start=None, end=None):  

返回子串sub在字符串中出现的次数

word = 'hello world'  print(word.count('o'))   # 2  

4. encode

方法定义

def encode(self, encoding='utf-8', errors='strict'):    

对字符串进行编码,返回的是bytes类型数据

word = 'hello world'  byte_word = word.encode(encoding='utf-8')  print(byte_word)   # b'hello world'  print(type(byte_word))  # <class 'bytes'>  

5. endswith

方法定义

def endswith(self, suffix, start=None, end=None)  

判断字符串是否以suffix结尾, 可以通过beg和 end来指定范围

word = 'hello world'  print(word.endswith('world'))  # True  

6. find

方法定义

def find(self, sub, start=None, end=None):      pass  

查找子串sub在字符串中的索引,如果找不到返回-1

word = 'hello world'  print(word.find('world'))  # 6  

7. index

方法定义

def index(self, sub, start=None, end=None):      pass  

跟find()方法一样,只不过如果sub不在字符串中会报一个异常

word = 'hello world'  print(word.index('world'))  # 6  

8. isalpha

字符串不是空串且都是字母,方法返回True

word = 'hello'  print(word.isalpha())  # True  

9. isalnum

字符串不是空串且都是字母或数字,方法返回True

word = 'hello23'  print(word.isalnum())  # True  

10. isdigit

如果字符串只包含数字(Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字)则返回 True 否则返回 False

word = '123'  print(word.isdigit())  # True  print("IV".isdigit())   # True 罗马数字也行  

11. islower

字符串里的字符都小写的,方法返回True

word = 'python'  print(word.islower())  # True  

12. isnumeric

如果字符串中只包含数字字符(Unicode数字,全角数字(双字节),罗马数字,汉字数字),则返回 True

print('23'.isnumeric())     # True  print('五十五'.isnumeric())    # True  

13. isspace

如果字符串里只包含空白符则返回True,空白符包括空格、回车符(r)、换行符(n)、水平制表符(t)、垂直制表符(v)、换页符(f)

word = ' tn'  print(word.isspace())   # True  

14. istitle

如果字符串是标题化的(见 title())则返回 True,否则返回 False

word = 'Hello Word'  print(word.istitle())  # True  

15. isupper

字符串里都是大写的字符,方法返回True

word = 'ABC'  print(word.isupper())  # True  

16 join

可以用来连接字符串

lst = ['hello', ' ', 'world']  print(''.join(lst))  # hello world  print('*'.join(lst)) # hello* *world  

17. len

返回字符串的长度

word = 'python'  print(len(word))  

18. ljust

方法定义

def ljust(self, width, fillchar=None):      pass  

返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。

word = 'python'  print(word.ljust(9, '*'))   # python***  

19. lower

将字符串中的大写字符转成小写字符

word = 'PYTHON'  print(word.lower()) # python  

20. lstrip

截掉字符串左边的空格或指定字符

word = ' python'  print(word.lstrip())    # python  

21. replace

方法定义

def replace(self, old, new, count=None):      pass  

将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 count 次

word = 'python'  print(word.replace('p', 'cp'))  # cpython  

22. rfind

方法定义

def rfind(self, sub, start=None, end=None):      pass  

类似于 find()函数,不过是从右边开始查找

word = 'python'  print(word.rfind('thon'))  # 2  

23. rindex

方法定义

def rindex(self, sub, start=None, end=None):      pass  

类似于 index(),不过是从右边开始

word = 'python'  print(word.rindex('thon'))  # 2  

24. rjust

方法定义

def rjust(self, width, fillchar=None):      pass  

返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串

word = 'python'  print(word.rjust(9, '*'))  

25. split

方法定义

def split(self, sep=None, maxsplit=-1):      pass  

以 sep为分隔符截取字符串

word = 'python'  print(word.split('t'))      # ['py', 'hon']  

26. splitlines

方法定义

def splitlines(self, keepends=None):      pass  

按照行('r', 'rn', n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

word = 'pyrtnhon'  print(word.splitlines())  # ['py', 't', 'hon']  

27. startswith

方法定义

def startswith(self, prefix, start=None, end=None):  

检查字符串是否是以指定子字符串 prefix 开头

word = 'python'  print(word.startswith('py'))  # True  

28. strip

在字符串上执行 lstrip()和 rstrip()

word = ' python '  print(word.strip()) # python  

29. swapcase()

将字符串中大写转换为小写,小写转换为大写

word = 'Python'  print(word.swapcase()) # pYTHON  

30. title()

返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())

word = 'hello world'  print(word.title())  # Hello World  

31. upper()

转换字符串中的小写字母为大写

word = 'hello world'  print(word.upper())  # HELLO WORLD  

32. zfill (width)

返回长度为 width 的字符串,原字符串右对齐,前面填充0

word = 'hello world'  print(word.zfill(20))  # 000000000hello world  

33. isdecimal()

检查字符串是否只包含十进制字符(Unicode数字,,全角数字(双字节)),如果是返回 true,否则返回 false

print('1233'.isdecimal())