解释、str.starswith()、str.endswith()、str.split()、 str.count()、str.strip())
时间: 2024-03-25 13:40:12 浏览: 23
- str.startswith(prefix[, start[, end]]):判断字符串是否以指定的前缀 prefix 开头,返回 True 或 False。可选的 start 和 end 参数表示搜索的起始位置和结束位置,默认为整个字符串。例如:
```
s = "hello world"
print(s.startswith("hello")) # 输出 True
print(s.startswith("world")) # 输出 False
```
- str.endswith(suffix[, start[, end]]):判断字符串是否以指定的后缀 suffix 结尾,返回 True 或 False。可选的 start 和 end 参数表示搜索的起始位置和结束位置,默认为整个字符串。例如:
```
s = "hello world"
print(s.endswith("world")) # 输出 True
print(s.endswith("hello")) # 输出 False
```
- str.split(sep=None, maxsplit=-1):将字符串按照指定的分隔符 sep 进行切分,返回切分后的字符串列表。可选的 maxsplit 参数表示最大切分次数,默认为 -1,表示不限制切分次数。例如:
```
s = "hello,world"
print(s.split(",")) # 输出 ['hello', 'world']
```
- str.count(sub[, start[, end]]):统计字符串中子串 sub 出现的次数,返回整数。可选的 start 和 end 参数表示搜索的起始位置和结束位置,默认为整个字符串。例如:
```
s = "hello world"
print(s.count("l")) # 输出 3
```
- str.strip([chars]):去掉字符串开头和结尾的空格或指定字符 chars,返回新字符串。可选的 chars 参数表示要去掉的字符集合,默认为 None,表示去掉空格。例如:
```
s = " hello world "
print(s.strip()) # 输出 "hello world"
```
另外还有 lstrip() 和 rstrip() 方法,分别表示去掉左侧和右侧的空格或指定字符。