常见字符串类型方法
1、find 方法
(1)参数说明及用法
find(sub, start=None, end=None)
# sub:查找的字符串
# start:起始索引
# end:结束索引
返回值为查找字符串的索引
(2)在索引start和end之间查找字符串sub找到,则返回最左端的索引值,未找到,则返回-1
source_str = "There is a string accessing example"
print(source_str.find('T', 2, 10))
# 输出结果
-1
(3)start和end都可省略,省略start说明从字符串开头找省略end说明查找到字符串结尾,全部省略则查找全部字符串
source_str = "There is a string accessing example"
print(source_str.find('T'))
# 输出结果
0
2、count 方法
(1)参数说明及用法
count(sub, start=None, end=None)
# sub:查找的字符串
# start:起始索引
# end:结束索引
返回值为查找字符串的个数
(2)返回字符串sub在start和end之间出现的次数
source_str = "There is a string accessing example"
print(source_str.count('e'))
print(source_str.count('e', 0, 4))
#输出结果
5
1
3、replace 方法
(1)参数说明及用法
replace(old, new, count=None)
# old代表需要替换的字符,new代表将要替代的字符,count代表替换的次数(省略则表示全部替换)
(2)效果展示
source_str = "There is a string accessing example"
print(source_str.replace('e', 'E'))
print(source_str.replace('e', 'E', 1))
# 结果展示
ThErE is a string accEssing ExamplE
ThEre is a string accessing example
4、spilt 方法
(1)参数说明及用法
split(sep, maxsplit=None)
# 以sep为分隔符切片,如果maxsplit有指定值,则仅分割maxsplit个字符串分割后原来的str类型将转换成list类型
(2)结果展示
source_str = "There is a string accessing example"
print(source_str.split('e'))
print(source_str.split('e', maxsplit=3))
# 输出结果
['Th', 'r', ' is a string acc', 'ssing ', 'xampl', '']
['Th', 'r', ' is a string acc', 'ssing example']
5、startswith 方法
(1)参数说明及用法
startswith(prefix, start=None, end=None)
# 判断字符串是否是以prefix开头,start和end代表从哪个下标开始,哪个下标结束
(2)结果展示
source_str = "There is a string accessing example"
print(source_str.startswith('T', 0, 10))
print(source_str.startswith('T'))
# 输出结果
True
True
6、endswith 方法
(1)参数说明及用法
endswith(suffix, start=None, end=None)
# 判断字符串是否以suffix结束,如果是返回True,否则返回False
(2)结果展示
source_str = "There is a string accessing example"
print(source_str.endswith('e'))
print(source_str.endswith('e', 0, 10))
# 输出结果
True
False
7、lower 方法
(1)参数说明及用法
source_str.lower()
(2)结果展示
source_str = "There is a string accessing example"
print(source_str.lower())
# 将所有字符串变小写
结果:
there is a string accessing example
8、upper 方法
(1)参数说明及用法
source_str.upper()
(2)结果展示
source_str = "There is a string accessing example"
print(source_str.upper())
# 将所有字符串变小写
结果:
THERE IS A STRING ACCESSING EXAMPLE
9、join 方法
(1)使用方法
# 将列表对象拼接成字符串
(2)结果展示
data = ['a', 'b', 'c']
print(''.join(data))
结果展示
abc
10、字符串翻转
source_str = "There is a string accessing example"
print(source_str[::-1])
结果展示
elpmaxe gnissecca gnirts a si erehT