Find count of sub_string in string [duplicate] - python

This question already has answers here:
String count with overlapping occurrences [closed]
(25 answers)
Closed 4 years ago.
Why is this giving output as 1 and not 2:
string = "ABCDCDC"
print(string.count("CDC"))
Also, since this is not working, how can I get 2 in this case?

You could use a regular expression to count overlapping substrings:
import re
string = "ABCDCDC"
print(len(re.findall('(?=CDC)', string))) # 2

Here is an algorithmic solution
string = "ABCDCDC"
sub_string = "CDC"
count = 0
for i in range(len(string)):
if string[i:len(sub_string)+i] == sub_string:
count += 1
print count

import re
print([m.start() for m in re.finditer('(?=CDC)', 'ABCDCDC')])
This should find all potentially overlapping occurences

You can try this simple way:
def overlapping_count(string, seek):
seek_len = len(seek)
return sum(c == seek[0] and string[i:i + seek_len] == seek
for i, c in enumerate(string))
string = "ABCDCDC"
print(overlapping_count(string, "CDC"))

Related

Finding a specific index? [duplicate]

This question already has answers here:
Determine prefix from a set of (similar) strings
(11 answers)
Closed 5 years ago.
If I have two strings, how can I find the index where the string stops matching?
'abcdefghijk' and the false alphabet 'abcdxyz', I know they stop matching at index 4, but how can I output that in a function setting?
Use the enumerate() function to find the index, for which the letter in the second string does not match the current letter in the first string -
def matcher(str1, str2):
for idx, item in enumerate(str1):
if item != str2[idx]:
return idx
return -1 # if no differing letter in second string
print(matcher('abcdefghijk', 'abcdxyz')) # 4
Using some simple comparisons of sliced strings:
We can create a simple function that keeps slicing the strings till it reaches the end of the first string and compares them:
def match(s1, s2):
for i in range(len(s1)+1):
if s1[:i] != s2[:i]:
return i - 1
return -1
and some tests:
>>> match('abcdefghijk', 'abcdxyz')
4
>>> match('124', '123')
2
>>> match('123456', '123abc')
3
>>> match("abcdef", "abcdef")
-1

Counting specific strings within another string [duplicate]

This question already has answers here:
String count with overlapping occurrences [closed]
(25 answers)
Closed 5 years ago.
I am trying to figure out how to count how many times one string appears in another string. My code that I'm trying to use and have played around with has not worked so far.
needle = input()
haystack = input()
count = 0
for needle in haystack:
count += 1
print(count)
My expected result if the input for haystack is 'sesses' and needle is 'ses' would be to print out 2. (ses is in haystack twice)
'sesses'.count('ses') will give you the answer
Use count()
needle = input()
haystack = input()
print haystack.count(needle)
for needle in haystack:
count += 1
The reason this doesn't work is that "for x in y" is iterating over values in y, and /placing/ them into x; it does not read from x. So in your code example, you are iterating over haystack (which, in Python, means looping through each letter), and then placing the value (each letter) into needle. Which is not what you want.
There's no built-in iterator to give you what you want -- an iterator of the occurrences of another string. haystack.count(needle) will give you the desired answer; other than that, you could also use haystack.find to find an occurrence starting at a given point, and keep track of how far you are in the string yourself:
index = haystack.find(needle)
while index >= 0:
count += 1
index = haystack.find(needle, index + 1)
Note that this will give a different answer than haystack.count: haystack.count will never count a letter twice, whereas the above will. So "aaaaaa".count("aaa") will return 2 (finding "aaaaaa" and "aaaaaa"), but the above code would return 4, because it would find "aaaaaa", "aaaaaa", "aaaaaa", and "aaaaaa".
Try this :)
characters = 'ses'
word = 'sesses'
chunkSize = 1
count = 0
while chunkSize < len(word):
for i in range(len(word) - chunkSize + 1):
if word[i:chunkSize+i] == characters:
count += 1
chunkSize += 1
print(count)
This should work:
a='seses'
b='se'
print a.count(b)
>>2

how to count the letters in a string? [duplicate]

This question already has answers here:
How to count digits, letters, spaces for a string in Python?
(12 answers)
Closed 5 years ago.
how do I code a program that would produce this below?
As an example, the following code fragment:
print (count_letters("ab1c2d345"))
should produce the output:
4
You can try this:
def count_letters(s):
return len([i for i in s if i.isalpha()])
print(count_letters('ab1c2d345'))
Output:
4
Or, you can use regex for a cleaner solution:
import re
def count_letters(s):
return len(re.findall('[a-zA-Z]', s))
You can do it using simple loop/if statement.
def count_letters(str_ltr):
count_ltr = 0
for ch in str_ltr:
if ch.isalpha():
count_ltr += 1
return count_ltr
print(count_letters("ab1c2d345"))
Output: 4

How to count the number of a specific character at the end of a string ignoring duplicates? [duplicate]

This question already has answers here:
Pythonic way to count the number of trailing zeros in base 2
(5 answers)
Closed 5 years ago.
I have a series of strings like:
my_text = "one? two three??"
I want to count only the number of ? at the end of the string. The above should return 2 (rather than 3).
What I've tried so far:
my_text.count("?") # returns 3
There's not a built-in method for it. But something simple like this should do the trick:
>>> len(my_text) - len(my_text.rstrip('?'))
2
You could also use a regexp to count the number of trailing question marks :
import re
def count_trailing_question_marks(text):
last_question_marks = re.compile("\?*$")
return len(last_question_marks.search(text).group(0))
print count_trailing_question_marks("one? two three??")
# 2
print count_trailing_question_marks("one? two three")
# 0
Not so clean but simple way:
my_text = "one? two three??"
total = 0
question_mark = '?'
i = 0
for c in my_text:
i -= 1
if my_text[i] == question_mark:
total += 1
else:
break
One-liner using my favourite itertools:
First reverse the string, then continue iterating (taking the values) while our condition is satisfied (value == '?'). This returns an iterable which we exhaust into a list and finally take its length.
len(list(itertools.takewhile(lambda x:x=='?',reversed(my_text))))

Count of a string in a list [duplicate]

This question already has answers here:
How do I count the occurrences of a list item?
(30 answers)
Closed 9 years ago.
I need help:
I want to write function that: takes a list as a input and return count of specific string.
If function input is x=[a,a,b,c] function need return 2 (a is two times in this list).
>>> def F(seq, string):
return seq.count(string)
>>> F(['a','a','b','c'], 'a')
2
Equivalent to:
def F(seq, string):
n = 0
for x in seq:
if x == string:
n += 1
return n

Categories