1.find
检测字符串是否包含指定字符,如果 是返回开始的索引值,否则返回-1
str = ‘hello world’
print(str.find(‘lo’))
输出3
2.index
检测字符串是否包含指定字符,如果是返回开始的索引值,否则提示错误
str = ‘hello world’
print(str.index(‘lo’))
输出3
3.count
返回str在string中指定索引范围内[start, end)出现的次数
str = ‘hello world’
print(str.count(‘lo’))
print(str.count(‘lo’,5,len(str)))
输出1,0
4.replace
将str中的str1替换成str2,如果指定 count,则不超过count次
str = ‘hello world hello china’
print(str.replace(‘hello’,‘HELLO’))
print(str.replace(‘hello’,‘HELLO’,1))
输出
HELLO world HELLO china
HELLO world hello china
5.split
以 str 为分隔符切片 mystr,如果 maxsplit有指 定值,则仅分隔 maxsplit 个子字符串
str = ‘hello world hello china’
print(str.split(’ ‘))
print(str.split(’ ',2))
输出
[‘hello’, ‘world’, ‘hello’, ‘china’]
[‘hello’, ‘world’, ‘hello china’]
6.capitalize
将字符串的首字母大写
str = ‘hello world hello china’
print(str.capitalize())
输出:Hello world hello china
7.title
将字符串中每个单词的首字母大写
str = ‘hello world hello china’
print(str.title())
输出:Hello World Hello China
8.startswith
检查字符串是否是以 obj 开头, 是则返回 True, 否则返回 False
str = ‘hello world hello china’
print(str.startswith(‘hello’))
输出 True
9.endswith
检查字符串是否是以 obj 结尾, 是则返回 True,否则 返回 False
str = ‘hello world hello china’
print(str.endswith(‘china’))
输出 True
10.lower
将字符串转换为小写
str = ‘Hello World HELLO CHINA’
print(str.lower())
输出:hello world hello china
11.upper
将字符串转换为大写
str = ‘hello world hello china’
print(str.upper())
输出:HELLO WORLD HELLO CHINA
12.ljust
返回一个原字符串左对齐,并使用空格填 充至长度 width 的新字符串
str = ‘hello’
print(str.ljust(10))
输出:hello (后面跟的有空格)
13.rjust
返回一个原字符串右对齐,并使用空格填 充至长度 width 的新字符串
str = ‘hello’
print(str.rjust(10))
输出: (前面有空格)hello
14.center
返回一个原字符串居中,并使用空格填充 至长度 width 的新字符串
str = ‘hello’
print(str.center(15))
输出: hello (左右两边都有空格)
15.lstrip
去除字符串左边空白字符
str = ’ hello’
print(str)
print(str.lstrip())
16.rstrip
去除字符串右边空白字符
str = 'hello ’
print(str)
print(str.lstrip())
17.strip
去除字符串两边空白字符
str = ’ hello ’
print(str)
print(str.lstrip())
18.partition
可以将字符串以str进行分割成三个部分 Str前,str,str后
str = ‘hello world hello china’
print(str.partition(‘world’))
输出
('hello ‘, ‘world’, ’ hello china’)
19.join
str 中每个字符后面插入str,构造出一 个新的字符串
str = ‘_’
list = [‘hello’,‘world’,‘hello’,‘china’]
str2 = ‘zhangsan’
print(str.join(str2))
print(str.join(list))
输出:
z_h_a_n_g_s_a_n
hello_world_hello_china
20.isspace
如果 str 中只包含空格,则返回 True, 否则返回 False.
str = ’ ’
print(str.isspace())
输出 True
21.isalnum
如果 str 所有字符都是字母或数字则返 回 True,否则返回 False
str = ‘a123’
print(str.isalnum())
输出 True
22.isdigit
如果 str 只包含数字则返回 True 否则 返回 False
str = ‘123’
print(str.isdigit())
输出 True
23.isalpha
如果 str 所有字符都是字母 则返回 True,否则返回 False
str = ‘abc’
print(str.isalpha())
输出 True
作者:__Y_Q
链接:https://www.jianshu.com/p/d273a3780b80
来源:简书