#查找相关
1 .find 找到元素返回 元素下标,找不到返回-1
ms = "hello world and can you help me and can you help me"
#字符串是不可变数据类型
#查找语法:字符串.find(子串,开始,结束),找不到则返回-1 ,找到返回第一个匹配项开始的下标
print(ms.find("can"))
# 返回坐标:16
print(ms.find("abs"))
#返回:-1
print(ms.find("can",18,100))
#返回坐标:36
2.查找语法:字符串.index(子串,开始,结束),找不到则报错,找到返回第一个匹配项开始的下标
#查找语法:字符串.index(子串,开始,结束),找不到则报错,找到则返回第一个匹配项开始的下标
ms = "hello world and can you help me and can you help me"
print(ms.index("can"))
#打印结果:16
print(ms.index("and",1,100))
#打印结果:12
print(ms.index("abs"))
#打印结果:substring not fount
总结,.find 和 .index的区别在于,当查找的元素找不到时,.find会返回-1 ,而.index会报错“substring not fount”
#修改相关
1.替换:字符串。replace("旧","新",替换次数)
ms = "hello world and can you help me and can you help me"
#替换
print(ms.replace("and","he"))
print(mx.replace("and","he",2))
字符串的分割
#字符串分割:字符串.splist(分割字符,分割次数),注意分割字符会被吃掉,分割次数不写默认全部分割
ms = "hello world and can you help me and can you help me"
ms.splist("and") #已空格为分割符号
返回结果:['hello world ', ' can you help me ', ' can you help me'] #保存到了列表,逗号隔开
字符串的拼接
#字符串拼接,拼接符 .join
list1 = ["can","you","help","me"]
a = " ".join(list1)
print(a)
功能性的修改
1.将字符串首字母大写,其他变成小写
2.将每个单词首字母大写
3.将全部字母大写
4.将全部字母变小写
ms = "hello word and can you help me"
#将字符串首字母大写
print(capitalize(ms))
#将单词首字母大写
print(title(ms))
#将全部字母大写
print(upper(ms))
#将全部字母小写
print(lowe(ms))
1.去除字符串两头的空白字符
2.去除左边的空白字符
3.去除右边空白字符
4.去除左边指定字符
5.去除右边指定字符
ms = " can you help me "
#1.去除字符串两头的空白字符
print(ms.strip())
2.去除左边的空白字符
print(ms.lstrip())
3.去除右边空白字符
print(ms.rstrip())
4.去除左边指定字符
print(ms.lstrip(ca))
5.去除右边指定字符
print(ms.rstrip(e))
#居中补全:
1.字符串center(长度,补全字符串)
2.靠左补全
3.靠右补全
s = "hello"
1.居中补全
print(s.center(11,"-"))
#靠左补齐
print(s.ljust(11.'-'))
#靠右补齐
print(s.rjust(11,"-"))
字符串的判断
1.判断字符串是否以某字符开头
2.判断是否以某字符结尾
ms = "can you help me"
#判断字符串是否已某个字符开头
print(startswith("can"))
#判断字符串是否以某个字符结尾
print(endswith("me"))
1.判断字符串是否以字母组成
2.判断字符串是否由数字组成
3.判断是否由字母或者数字组成
4.判断字符串是否全由空白字符组成
ms = "can you help me"
#1.判断字符串是否由字母组成
print(ms.isalpha())
#2.判断字符串是否由数字组成
print(ms.isdigit())
#3.判断字符串是否由字母或数字组成
print(ms.isalnum())
4.判断字符串是否由空白字符组成
print(ms.isspace())