Sometimes it is quite fun to answer some questions in Stackoverflow: you can help someone seeking answer and you may also learn a new thing or two yourself in the process.
This is one such example:
http://stackoverflow.com/questions/11707151/python-make-a-global-condition-break.
Essentially the OP is asking if there is an easy to find the number of occurrence of a substring in a longer string. For example “assesses” has the substring “sses” 2 times.
It is a very simple question, but there is still something new I learn: while re.findall
is the most elegant solution, it may not work in finding overlapped occurrence of pattern. To do so one needs to include a ‘lookahead’ in the regular expression.
My proposed solution is simply an improved version of OP’s code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Here is a even shorter version which takes advantage of python’s flexible comparison syntax:
1 2 3 4 5 6 7 8 9 10 11 12 |
|