Count number of occurrences of a given substring in a string

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

    Depending what you really mean, I propose the following solutions:

    1. You mean a list of space separated sub-strings and want to know what is the sub-string position number among all sub-strings:

      s = 'sub1 sub2 sub3'
      s.split().index('sub2')
      >>> 1
      
    2. You mean the char-position of the sub-string in the string:

      s.find('sub2')
      >>> 5
      
    3. You mean the (non-overlapping) counts of appearance of a su-bstring:

      s.count('sub2')
      >>> 1
      s.count('sub')
      >>> 3
      

提交回复
热议问题