By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,905 Members | 2,075 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,905 IT Pros & Developers. It's quick & easy.

counting a collection of letters within a string

P: 3
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

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

Any suggestions gratefully received!
Thanks!
Jun 20 '14 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 621
You have to create your own code when builtins assume things you don't want.
Expand|Select|Wrap|Line Numbers
  1. s = 'ajsfhbababnsnbabnndbab'
  2. found=0
  3. location = -1
  4. while True:
  5.     location = s.find("bab", location+1)
  6.     if location > -1:
  7.         found += 1
  8.     else:
  9.         break
  10.  
  11. print 'Number of times bab occurs is: %s' % (found) 
Jun 20 '14 #2

bvdet
Expert Mod 2.5K+
P: 2,851
Create your own count function using string slice. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> def count_str(s, find_str):
  2. ...     count = 0
  3. ...     for i in range(len(s)):
  4. ...         if s[i:i+len(find_str)] == find_str:
  5. ...             count += 1
  6. ...     return count
  7. ... 
  8. >>> s = 'ajsfhbababnsnbabnndbab'
  9. >>> count_str(s, "bab")
  10. 4
  11. >>> 
Jun 20 '14 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Here's the function in my previous post as a list comprehension:
Expand|Select|Wrap|Line Numbers
  1. >>> s = 'ajsfhbababnsnbabnndbab'
  2. >>> find_str = "bab"
  3. >>> [s[i:i+len(find_str)] == find_str for i in range(len(s))].count(True)
  4. 4
  5. >>> 
Jun 22 '14 #4

Post your reply

Sign in to post your reply or Sign up for a free account.