我有一个像这样的字符串:
string1 = "foo_bar_of_foo"
string2 = "foo_bar"
This的答案告诉我如何检查字符串中的“ foo”实例,但是如果我想检查字符串中的 n 个“ foo”实例,该怎么办? ?
例如:
#pseudo-code = find(2 instances of foo)
if "foo" in string1:
print("true") #this should print
if "foo" in string2:
print("false") #this shouldn't print since string2 only has 1 instance of foo
我可以想到执行此操作的漫长而复杂的方法,但是我想知道 pythonic 方法是什么吗?
答案 0 :(得分:1)
只需使用str.count
:
string1 = "foo_bar_of_foo"
string2 = "foo_bar"
if string1.count('foo') == 2:
print("true")
if string2.count('foo') == 2:
print("false")