1. 输入两个字符串str1、str2,统计字符串str2出现在str1中的次数。
时间: 2024-03-10 16:51:00 浏览: 15
好的,我可以帮你解决这个问题。以下是 Python 代码实现:
```python
def count_substring(str1, str2):
count = 0
index = 0
while True:
index = str1.find(str2, index)
if index != -1:
count += 1
index += len(str2)
else:
break
return count
```
这个函数接收两个字符串 `str1` 和 `str2` 作为参数,然后使用 `find` 函数在 `str1` 中查找 `str2`,并统计出现次数。你可以通过调用这个函数来解决你的问题。
相关问题
输入两个字符串str1、str2,统计字符串str2出现在str1中的次数
可以使用 Python 的字符串函数 count() 来统计字符串出现的次数。
示例代码:
```python
str1 = "hello world, world is beautiful"
str2 = "world"
count = str1.count(str2)
print(f"{str2}出现在{str1}中的次数为:{count}")
```
输出结果为:
```
world出现在hello world, world is beautiful中的次数为:2
```
其中,count() 函数会返回字符串 str2 在字符串 str1 中出现的次数。
python输入两个字符串str1、str2,统计字符串str2出现在str1中的次数。
好的,可以使用 Python 的 count() 方法来实现统计字符串出现的次数,代码如下:
```python
str1 = input("请输入字符串str1:")
str2 = input("请输入字符串str2:")
count = str1.count(str2)
print("字符串str2在str1中出现的次数为:", count)
```
其中,count() 方法返回字符串中某个字符或子字符串出现的次数。以上代码中,我们先使用 input() 函数获取用户输入的两个字符串 str1 和 str2,然后使用 count() 方法统计 str2 在 str1 中出现的次数,并将结果输出到控制台上。