[英]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.