如何计算字符串是否在列表的子字符串中?

时间:2018-10-07 18:29:36

标签: python python-3.x

例如:

list_strings = 'dietcoke', 'dietpepsi', 'sprite' 

这就是我所做的:

count = 0
list =
for ch in list_strings:

    if ch == sub:
        count += 1

print((list_strings, 'diet') == 2)应该返回True,但它返回False

1 个答案:

答案 0 :(得分:1)

希望我能正确理解你。

只需使用in检查主字符串中是否存在子字符串。

list = ['dietcoke', 'dietpepsi', 'sprite']

您的函数应如下所示:

def myfuncname(list_strings, sub_string):
    count = 0
    for ch in list_strings:
        if sub_string in ch:
            count += 1
    return count

如果我们现在致电计数,我们将获得count == 2

>>> print(myfuncname(list_strings, 'diet') == 2) 
True

希望能解决您的问题。

相关问题