Count number of occurrences of a given substring in a string

后端 未结 30 2002
不思量自难忘°
不思量自难忘° 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:55

    One way is to use re.subn. For example, to count the number of occurrences of 'hello' in any mix of cases you can do:

    import re
    _, count = re.subn(r'hello', '', astring, flags=re.I)
    print('Found', count, 'occurrences of "hello"')
    

提交回复
热议问题