怎样字符串.count有用吗?

2024-05-13 16:42:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和学习的新手。正如给定的herecount()方法在字符串上使用时给出了字符串中子字符串的出现次数。在

所以当我这么做的时候:

'BANANA'.count('ANA')

预期输出应为2,因为“ANA”在“BANANA”中出现两次,但count返回1。在

有人能解释一下吗,或者我误解了什么。在

请给我指一下正确的方向。在


Tags: 方法字符串count方向次数banana中子新手
2条回答

您可以使用正则表达式来查找它。使用来自模块re的函数findall查找重叠出现

import re
len(re.findall('(?=ANA)', 'BANANA'))

结果是2。在

或者在这里得到3:

^{pr2}$
>>> help(str.count)
Help on method_descriptor:

count(...)
    S.count(sub[, start[, end]]) -> int

    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.

注意不重叠。在

相关问题 更多 >