Count number of occurrences of a given substring in a string

后端 未结 30 2130
不思量自难忘°
不思量自难忘° 2020-11-22 13:58

How can I count the number of times a given substring is present within a string in Python?

For example:

>>> \'foo bar foo\'.numberOfOccurre         


        
30条回答
  •  星月不相逢
    2020-11-22 14:50

    my_string = """Strings are amongst the most popular data types in Python. 
                   We can create the strings by enclosing characters in quotes.
                   Python treats single quotes the same as double quotes."""
    
    Count = my_string.lower().strip("\n").split(" ").count("string")
    Count = my_string.lower().strip("\n").split(" ").count("strings")
    print("The number of occurance of word String is : " , Count)
    print("The number of occurance of word Strings is : " , Count)
    

提交回复
热议问题