简体   繁体   English

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

[英]How do I count if a string is within the substrings of a list?

For example:例如:

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

Here's what I did:这是我所做的:

count = 0
list =
for ch in list_strings:

    if ch == sub:
        count += 1

print((list_strings, 'diet') == 2) is suppose to return True but it returns False . print((list_strings, 'diet') == 2)假设返回True但它返回False

I hope I understood you correctly.我希望我能正确理解你。

Just use in to check if your substring is present in the mainstring.只需使用in检查您的子字符串是否存在于主字符串中。

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

Your function should look like this:您的函数应如下所示:

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

If we call count now, we get count == 2如果我们现在调用count,我们得到count == 2

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

Hope that solved your problem.希望解决了你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Python 中的给定字符串中删除子字符串列表? - How do I remove a list of substrings from a given string in Python? 如何检查字符串列表中是否存在字符串,包括子字符串? - How do I check existence of a string in a list of strings, including substrings? 如何从XML xpath搜索生成的列表中的子字符串中删除字符? - How do I strip characters from substrings within a list generated from an XML xpath search? 如何计算格式非常明确的文件中的对象/子字符串? - How do I count objects/substrings in a very specifically formatted file? 正则表达式如何检查子字符串列表是否出现在字符串之前? - How to do regex check if a list of substrings appears before a string? 如何从字符串中找到子串列表的位置? - How can I find the position of the list of substrings from the string? 如何在python字符串中的子字符串之间找到子字符串? - How to find substrings between substrings within a python string? 如何删除 Python 字符串中以大写字母开头的子字符串? - How do I remove the substrings started with capital letters in a Python string? 如何通过递归获取字符串的所有连续子字符串? - How do I get all consecutive substrings of a string with recursion? 如何获取一定长度范围内的子字符串列表? - How to get list of substrings within a range of lengths?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM