【问题标题】:How to check for multiple occurences of a substring in a string? [duplicate]如何检查字符串中子字符串的多次出现? [复制]
【发布时间】:2019-07-14 13:43:24
【问题描述】:

我有这样的字符串:

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 方法是什么?

【问题讨论】:

    标签: python python-3.x


    【解决方案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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 2012-12-26
      • 2010-10-20
      相关资源
      最近更新 更多