4

If this is the first string : ABCD

if this is the second string: ABCD is ABCD

I want to count the occurrence of first string in the second string and that too in python. How can I do that?I'm new to python, so facing some problems. Can anyone tell me the solution or provide the code for the same.

1 Answer 1

3

Use str.count():

>>> str1 = "ABCD"
>>> str2 = "ABCD is ABCD"
>>> str2.count(str1)
2
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks it worked , The solution was so simple, it skipped from my mind that I can use count :)
@POOJAGUPTA yes it was simple. You can accept the solution if it worked for you.
If str1 = "AA" and str2 = "AAAA" then the output is 2 if count() is used. But, it is not correct, right ? I think the correct output is 3. Because, 1st substring is index 0 & index 1 together. 2nd substring is index 1 & index 2 together. 3rd substring is index 2 & index 3. So, the correct output is 3, right ? Please clarify.
@RajKumarRampelli Nop, 2 is the correct output in that case as it returns the number of non-overlapping occurrences. To get the overlapping count you can use regex: len(re.findall('(?=AA)', 'AAAA')) == 3.
The re.findall('(?=AA)', 'AAAA') expression return the list [' ', ' ', ' '] and which is of length 3. When I used regex 'AA' instead of '(?=AA)' then the output is ['AA', 'AA']. My query is why the output doesn't contain substrings 'AA' when regex '(?=AA)' used ? also, what is the use of '?=' ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.