编写一个函数,该函数可以统计一个长度为3的字符串在另一个字符串中出现的次数。例如,假定输入的字符串为:asdasasdfgasdaszx67asdmklo,字符串为:asd,则应输出n=4。。
时间: 2023-04-24 15:03:48 浏览: 174
可以编写一个函数,接收两个参数,一个是待查找的字符串,一个是目标字符串。函数的实现思路如下:
1. 定义一个计数器变量n,初始值为0。
2. 使用循环遍历目标字符串,每次取出长度为3的子串,判断该子串是否等于待查找的字符串。
3. 如果相等,则将计数器n加1。
4. 循环结束后,返回计数器n的值。
函数的代码如下:
```
def count_str(str1, str2):
n = 0
for i in range(len(str2)-2):
if str2[i:i+3] == str1:
n += 1
return n
```
使用示例:
```
s = 'asdasasdfgasdaszx67asdmklo'
sub = 'asd'
n = count_str(sub, s)
print(n) # 输出 4
```
在这个示例中,待查找的字符串为'asd',目标字符串为'asdasasdfgasdaszx67asdmklo',函数返回值为4,表示'asd'在目标字符串中出现了4次。
相关问题
编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数
可以使用Python中的count()函数来实现统计一个长度为2的字符串在另一个字符串中出现的次数。具体实现如下:
def count_str(str1, str2):
count =
for i in range(len(str2)-1):
if str2[i:i+2] == str1:
count += 1
return count
其中,str1表示要统计的长度为2的字符串,str2表示要在其中统计出现次数的字符串。函数中使用了一个计数器count来记录出现次数,然后使用for循环遍历str2中的每个长度为2的子字符串,如果该子字符串与str1相等,则计数器加1。最后返回计数器的值即可。
编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数。
以下是 Python 3 的实现代码:
```python
def count_occurrences(string, substr):
count = 0
for i in range(len(string) - 1):
if string[i:i + 2] == substr:
count += 1
return count
```
函数接收两个参数:`string` 和 `substr`,分别表示目标字符串和需要统计的子字符串。该函数使用一个计数器变量 `count` 来统计子字符串出现的次数。然后使用 `range()` 函数遍历目标字符串中的每个位置,判断该位置和下一位置组成的两个字符是否和子字符串相等,如果相等就将计数器加一。最后返回计数器的值即可。
下面给出一个简单的测试:
```python
string = 'hello world'
substr = 'lo'
count = count_occurrences(string, substr)
print(count) # 输出:2
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)