确定子字符串在 Python 中的字符串中出现的次数 [英] Determining how many times a substring occurs in a string in Python

查看:49
本文介绍了确定子字符串在 Python 中的字符串中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚一个字符串在一个字符串中出现了多少次.例如:

nStr = '000123000123'

假设我要查找的字符串是 123.显然它在 nStr 中出现了两次,但是我在将这个逻辑实现到 Python 中时遇到了麻烦.我目前得到的:

pattern = '123'计数 = a = 0nStr[a:] 中的 while 模式:a = nStr[a:].find(pattern)+1计数 += 1返回计数

它应该返回的答案是 2.我现在陷入了无限循环.

我刚刚意识到计数是一种更好的方法,但出于好奇,有没有人看到类似于我已经得到的方法?

解决方案

使用 str.count:

<预><代码>>>>nStr = '000123000123'>>>nStr.count('123')2

代码的工作版本:

nStr = '000123000123'模式 = '123'计数 = 0标志 = 真开始 = 0而标志:a = nStr.find(pattern, start) # find() 如果没有找到这个词则返回 -1,#start i 从搜索开始的起始索引(默认值为 0)if a == -1: #if 模式未找到设置标志为 False标志 = 错误else: # 如果找到单词增加计数并将起始索引设置为 a+1计数 += 1开始 = a + 1打印(计数)

I am trying to figure out how many times a string occurs in a string. For example:

nStr = '000123000123'

Say the string I want to find is 123. Obviously it occurs twice in nStr but I am having trouble implementing this logic into Python. What I have got at the moment:

pattern = '123'
count = a = 0
while pattern in nStr[a:]:
    a = nStr[a:].find(pattern)+1
    count += 1
return count

The answer it should return is 2. I'm stuck in an infinite loop at the moment.

I was just made aware that count is a much better way to do it but out of curiosity, does anyone see a way to do it similar to what I have already got?

解决方案

Use str.count:

>>> nStr = '000123000123'
>>> nStr.count('123')
2

A working version of your code:

nStr = '000123000123'
pattern = '123'
count = 0
flag = True
start = 0

while flag:
    a = nStr.find(pattern, start)  # find() returns -1 if the word is not found, 
    #start i the starting index from the search starts(default value is 0)
    if a == -1:          #if pattern not found set flag to False
        flag = False
    else:               # if word is found increase count and set starting index to a+1
        count += 1        
        start = a + 1
print(count)

这篇关于确定子字符串在 Python 中的字符串中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆