python计算字符串中子串次数代码
时间: 2023-06-02 22:07:47 浏览: 73
以下是计算字符串中子串次数的 Python 代码:
```python
def count_substring(string, sub_string):
count = 0
start = 0
while True:
start = string.find(sub_string, start) + 1
if start > 0:
count += 1
else:
return count
```
你可以调用这个函数,传入要计算的字符串和子字符串作为参数,它会返回子字符串在原字符串中出现的次数。
相关问题
python统计字符串中子串出现的次数
可以使用Python中的字符串函数count()来统计子串在字符串中出现的次数。例如:
```python
s = 'python练习字符串中子串出现的次数'
sub = '字符串'
count = s.count(sub)
print(count) # 输出2
```
以上代码中,字符串s为要统计的字符串,子串sub为要计算出现次数的子串。使用count()函数即可返回子串在字符串中出现的次数。
用Python编写一个程序,计算字符串中子串出现的次数
可以使用Python中的count函数,该函数可以用于计算一个字符串中某个子串出现的次数。示例代码如下:
```python
string = 'hello world, hello python, hello world'
sub_string = 'hello'
count = string.count(sub_string)
print(count)
```
输出结果为:
```
3
```
表示子串'hello'在字符串中出现了3次。