python: Finding a substring within a string -
i'm trying write programme counts how many times substring appears within string.
word = "wejmfoiwstreetstreetskkjoih" streets = "streets" count = 0 if streets in word: count += 1 print(count) as can see "streets" appears twice lastly s of streets origin of streets. can't think of way loop this.
thanks!
can done using regex
>>> import re >>> text = 'streetstreets' >>> len(re.findall('(?=streets)', text)) 2 from the docs:
(?=...)
matches if ... matches next, doesn’t consume of string. called lookahead assertion. example, isaac (?=asimov) match 'isaac ' if it’s followed 'asimov'.
python
No comments:
Post a Comment