473,548 Members | 2,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

counting a collection of letters within a string

3 New Member
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
3 1258
dwblas
626 Recognized Expert Contributor
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
2,851 Recognized Expert Moderator Specialist
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
2,851 Recognized Expert Moderator Specialist
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

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

Similar topics

2
2747
by: colm | last post by:
I have a string surname and want to select the first two letters to use in a code field how can i check if the second item in string is an apostrophe and filter it out ' in names such as o'brien and use the third item in string so i get ob in other words if surname = brown code =br but if surname = o'brien code = ob colm
1
1080
by: Shafia | last post by:
Hi, I need to refresh the Rows collection of my GridView within a tree event OnCheckChanged. I call the following for that void OnCheckChanged(....) { ...................
24
2297
by: Derek Hart | last post by:
Is there an efficient line of code to count the number of instances of one string within another. If I have the sentence: "I want to go to the park, and then go home." It would give me a count of 2 for the word "go" Derek
4
9341
by: John | last post by:
1. Is there an easy function in VB to count for instance the number of A's in a string? 2. Is there an easy funtion in VB to pull all characters out of a string into an array? (I tried the split function but that needs a separator.) Thanks, john
8
2157
by: aboon | last post by:
Hi, I really need you guys' help with getting string within string. I have an address validation code that will send a request string to UPS, and if the address is validated, UPS will send a response string back. The problem starts here. Once I get the response string, I want to be able to display only city, state and zipcodes, but I don't know...
1
1668
by: nivedita prasad | last post by:
hi Occurrence of letters in String. Get string from KB of any length & print letters coming maximum time first than second largest….. i.e in descending order. program should be implemented using link list n dymami memory allocation. Output look like if u enter string aababbbcba b 5 times a 4 times c 1...
6
15011
by: peridian | last post by:
I've got some odd behaviour in a foreach loop, could anybody explain why this occurs? Simple class: public class ImageBindingObject { public ImageInfo ImageInfo { get; set; } public bool Selected { get; set; } }
2
2206
by: Udara chathuranga | last post by:
I need to use Sinhalese language Unicode letters within my personal web site. How can I do that ? Are their any special tags to insert Unicode letters? Final result should be like this web page. There are Sinhalese letters and they are displayed on the browser. http://mahamevnawa.blogspot.com/2011/01/blog-post.html
2
2580
by: Maris Neteiksu | last post by:
Hello, I have a variable string, named "line", a person writes some random stuff in it, and I need to count how many letters are in his text, how many numbers, and then how many other symbols. I have no idea how to do it. Hope you can help. This is what I have right now: string line= ""; Console.Write("Write your...
0
7444
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7711
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7954
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7805
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6039
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5367
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3497
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3478
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1054
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.