Files
2025PY/day20/06-字符串的方法.py
2025-05-22 16:50:44 +08:00

38 lines
1013 B
Python

# 1、str.split(参数1,maxsplit=参数2) 返回一个列表 参数1为分隔符 参数2表示分隔符前几个字符
# 将字符串利用分隔符转换为列表
# 默认以空格作为分隔符来分割字符串
# 当字符串不存在空格的时候 即无法分割时 将输出一个只有一个字符串元素的列表
str='a b c d e f g'
print(str.split()) #['a', 'b', 'c', 'd', 'e', 'f', 'g']
str1='abcdefgh'
print(str1.split()) #['abcdefgh']
# str.split(参数1,maxsplit=参数2) 返回一个列表 参数1为分隔符
str2='a,b,c,d,e,f,g,h'
print(str2.split(',')) #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
# 最大分隔数 参数2表示分隔符前几个字符
str='a b c d e f g'
print(str.split(' '))
print(str.split(' ',maxsplit=3))
print(str.split(' ',maxsplit=4))
# 2、str.count(sub,start,end) 返回str中sub在区间的次数 start,end表示区间可以省略
str='hello,zhangsan,lisi,hello,wangwu'
print(str.count('hello'))
print(str.count('hello',0,10))
print(str.count('l'))