编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为: asd asasdfg asd as zx67 asd mklo,子字符串为:as,则应输出6。
时间: 2024-02-27 16:57:49 浏览: 19
好的,以下是符合您要求的Python函数代码:
```python
def count_substring(string, sub_string):
count = 0
for i in range(len(string) - 1):
if string[i:i+2] == sub_string:
count += 1
return count
```
使用示例:
```python
string = 'asd asasdfg asd as zx67 asd mklo'
sub_string = 'as'
print(count_substring(string, sub_string))
# 输出:6
```
该函数通过遍历原字符串中的每个长度为2的子字符串,判断其是否与子字符串相等,若相等则计数器加1,最后返回计数器的值。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)