有人可以分解此代码以防止在Python中发生不重叠的情况吗?

时间:2018-08-04 13:01:12

标签: python string count substring

假设计数不存在。

string = 'let it be let it'
substring = 'let it'
count = 0
sub_len = len(substring) 
for i in range(len(string)): 
    if string[i:i+sub_len] == substring:
        count += 1
print(count)
>>> 2

这部分确实让我感到困惑

for i in range(len(string)):
    if string[i:i+sub_len] == substring:
        count += 1

更具体地说

    if string[i:i+sub_len] == substring:

我不知道这如何增加计数?

有人可以向我解释这一点,尤其是括号中的部分。

1 个答案:

答案 0 :(得分:0)

Python具有称为slicing的功能,通过指定开始和结束标记(其中包括开始和结束),您可以从字符串中提取子字符串。

其语法为:

some_string[start:stop:step]

所有都是可选的。

因此,文档中的一些示例(如上链接):

>>> word = 'Python'
>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'
>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

并给出一个包含step的内容:

>>> word[::2]
'Pto'

因此,为了解释您的代码,使用了一个for循环来迭代切片的起始索引。当然,这些索引的范围从0range()函数的默认值)到整个字符串的长度。

在您的情况下,由于string的长度为16,因此变量i将采用以下值:01,{{1 }} ... 214

然后,您从以索引15开始并以索引i + i结束的字符串中获取切片。由于sub_len是子字符串的长度,因此将从sub_len中获取与子字符串大小(长度)相同的切片。

例如,第一个是:

string

现在,等价比较器('let it' 'et it ' 't it b' ... 'let it' )用于检查此子字符串是否等于所需的子字符串-如果是,则将count变量递增。

相关问题