函数&方法 | 描述 | 示例 |
find | 检测字符串是否包含指定字符,如果是返回开始的索引值,否则返回-1 | str1 = 'hello world' print(str1.find('lo')) |
index | 检测字符串是否包含指定字符,如果是返回开始的索引值,否则提示错误 | str1 = 'hello world' print(str1.index('lo'))
|
count | 返回str1在string中指定索引范围内[start,
end)出现的次数 | str1 = 'hello world' print(str1.count('lo')) print(str1.count('lo',5,len(str11))) |
replace
|
将str1中的str1替换成str2,如果指定count,则不超过count次 | str1= 'hello world hello china' print(str1.replace('hello','HELLO')) print(str1.replace('hello','HELLO',1)) |
函数&方法 | 描述 | 示例 |
split | 如果 maxsplit有指定值,则仅分割 maxsplit 个子字符串 | str1 = 'hello world hello china' print(str1.split(' ')) print(str1.split(' ',2)) |
capitalize | 将字符串的首字母大写 | str1 = 'hello world hello china' print(str1.capitalize()) |
title | 将字符串中每个单词的首字母大写 | str1 = 'hello world hello china' print(str1.title()) |
startswith
| 检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False | str1 = 'hello world hello china' print(str1.startswith('hello')) |
endswith
| 检查字符串是否是以 obj 结尾, 是则返回 True,否则返回 False
| str1 = 'hello world hello china' print(str1.endswith(‘china'))
|
函数&方法 | 描述 | 示例 |
lower | 将字符串转换为小写 | str1 = 'Hello World HELLO CHINA' print(str1.lower()) |
upper | 将字符串转换为大写 | str1 = 'hello world hello china' print(str1.upper()) |
ljust | 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串 | str1 = 'hello' print(str1.ljust(10)) |
rjust
| 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串 | str1 = 'hello' print(str1.rjust(10))
|
center | 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串 | str1 = 'hello' print(str1.center(15))
|
函数&方法 | 描述 | 示例 |
lstrip | 去除字符串左边空白字符 | str1 = ' hello' print(str1) print(str1.lstr1ip()) |
rstrip | 去除字符串右边空白字符 | str1 = 'hello ' print(str1) print(str1.lstr1ip())
|
strip | 去除字符串两边空白字符 | str1 = ' hello ' print(str1) print(str1.lstr1ip())
|
partition
| 可以将字符串以str1进行分隔成三个部分 str1前,str1,str1后 | str1 = 'hello world hello china' print(str1.partition('world'))
|
函数&方法 | 描述 | 示例 |
join | str1 中每个字符后面插入str1,构造出一个新的字符串 | str1 = '_' list = ['hello','world','hello','china'] print(str1.join(list)) |
isspace | 如果 str1 中只包含空格,则返回 True,否则返回 False. | str1 = ' ' print(str1.isspace()) |
isalnum | 如果 str1 所有字符都是字母或数字则返回 True,否则返回 False | str1 = 'a123' print(str1.isalnum()) |
isdigit
| 如果 str1 只包含数字则返回 True 否则返回 False | str1 = '123' print(str1.isdigit()) |
isalpha
| 如果 str1 所有字符都是字母 则返回 True,否则返回 False | str1 = ‘abc' print(str1.isalpha()) |