为什么“www.count”(“ww”)返回1而不是2?

2024-10-04 09:18:34 发布

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

在我的代码中:

>> s = 'abacaba'
>> s.count('aba')
>> 2

对于上面的代码,我得到了正确的答案,因为'aba'在字符串s中出现了2次。

但对于以下情况:

>> s = 'www'
>> s.count('ww')
>> 1

在这种情况下,我希望s.count('ww')将返回2。但它返回1

为什么?


Tags: 字符串答案代码wwwcount情况wwaba
3条回答

string.count(s, sub[, start[, end]]):

Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.

来源:https://docs.python.org/2/library/string.html

试着想象一下:

在“ababa”这个词中,你看到多少个不重叠的“aba”字?我看到2。我也看到一个“c”。

在这个词中:“www”你看到多少个不重叠的“ww”字?我明白了。我也看到一个“w”。

为了得到更好的解释,当您看到实例时,可以认为您正在删除它。

对于“abacaba”,您可以看到“aba”并将其删除。现在有了“caba”,你再次看到“aba”并删除它。现在你只得到“c”。你看了两遍“aba”。对于“www”也是一样的,你只需看到一次“ww”就可以删除它。现在你只看到“w”。你只看过一次“ww”。

这是有道理的。

阅读docs

Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.

因为“w w”是第一个匹配的,所以它从第三个“w”开始,但无法匹配“ww”。

相关问题 更多 >