counting a collection of letters within a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • blackpaddycat
    New Member
    • Jun 2014
    • 3

    counting a collection of letters within a string

    Hi
    I am trying to write code that will return all instances of a collection of letters in a string variable...
    I can get a count returned, but it does not cater for letters that are used twice... for example

    Code:
    s = 'ajsfhbababnsnbabnndbab'
    n = s .count (str('bab'))
    print 'Number of times bab occurs is: ' + str(n)
    The code returns 3 instances but actually it is 4 - it is not counting the babab as 2 instances.

    Any suggestions gratefully received!
    Thanks!
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    You have to create your own code when builtins assume things you don't want.
    Code:
    s = 'ajsfhbababnsnbabnndbab'
    found=0
    location = -1
    while True:
        location = s.find("bab", location+1)
        if location > -1:
            found += 1
        else:
            break
    
    print 'Number of times bab occurs is: %s' % (found)

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Create your own count function using string slice. Example:
      Code:
      >>> def count_str(s, find_str):
      ... 	count = 0
      ... 	for i in range(len(s)):
      ... 		if s[i:i+len(find_str)] == find_str:
      ... 			count += 1
      ... 	return count
      ... 
      >>> s = 'ajsfhbababnsnbabnndbab'
      >>> count_str(s, "bab")
      4
      >>>

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Here's the function in my previous post as a list comprehension:
        Code:
        >>> s = 'ajsfhbababnsnbabnndbab'
        >>> find_str = "bab"
        >>> [s[i:i+len(find_str)] == find_str for i in range(len(s))].count(True)
        4
        >>>

        Comment

        Working...