在 Python 中计算子字符串 - 更有效的方法? [英] Counting substrings in Python - more efficient approach?

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

问题描述

所以我已经学习 Python 几个月了.我遇到了一个练习,它希望您计算子字符串在字符串中出现的次数.我进行了搜索,但找不到我正在寻找的确切答案.这是我写的代码,这是功能性的.但是,由于异常,它确实需要一秒钟.我选择使用 string.index 是因为在某些单词中 string.find 的 -1 值会弄乱起点.在不导入其他模块等的情况下,更有效的方法是什么.在更基础的 Python 中,比如我写的代码.

word = "banana"sub = "ba"开始 = 0ix = 0计数 = 0结束 = 无如果结束是无:结束 = len(字)而开始 <结尾:如果子在单词中:尝试:ix = word.index(sub, start, end)除了:休息ix += 1开始 = ix + 1计数 += 1打印(计数)

谢谢!

解决方案

你可以这样做:

'banana'.count('ba')

字符串计数方法的文档说:

<块引用>

返回子串sub中非重叠出现的次数字符串 S[开始:结束].可选参数开始和结束是解释为切片符号.

示例输出:

<预><代码>>>>'香蕉'.count('ba')1>>>'香蕉'.count('na')2

So I've been learning Python for a couple months now. I came across an exercise that wants you to count how many times a sub-string appears in a string. I searched, but couldn't find quite the exact answer I was looking for. Here is the code I wrote, that is functional. However, it does take a second due to the exception. I chose to use string.index because the -1 value from string.find in some words would mess up the starting point. What is the more efficient way, without importing other modules, etc. E.g. in more basic Python, such as the code I wrote.

word = "banana"
sub = "ba"
start = 0
ix = 0
count = 0
end = None

if end is None:
    end = len(word)
while start < end:
    if sub in word:
        try:
            ix = word.index(sub, start, end)
        except:
            break
        ix += 1
        start = ix + 1
        count += 1
print(count)

Thanks!

解决方案

You could just do:

'banana'.count('ba')

The docs for the count method of strings say:

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Sample output:

>>> 'banana'.count('ba')
1
>>> 'banana'.count('na')
2

这篇关于在 Python 中计算子字符串 - 更有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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