[Tutor] pattern searching
bob gailer
bgailer at gmail.com
Sat Nov 7 02:50:50 CET 2009
Ajith Gopinath wrote:
> Hi,
>
> How to find out all the occuerence of a particular pattern like in a
> long text where a capital letter in between two small letters
> ('aBa','dAd' etc..)
The other proposals are all good. However if performance is a concern
then I'd use string.maketran to create a translation table, then apply
it to the text using translate, such that all lower case letters are
translated to 'l', all upper case letters to 'u', then look for 'lul'.
import string
translationTable = string.maketrans(string.ascii_uppercase +
string.ascii_lowercase, 'u'*26 + 'l'*26)
translatedText = text.translate(translationTable)
start = 0
while True:
start = translatedText.find('lul', start)
if start >= 0:
print text[start:start+3]
else:
break
Translate and find are both very fast.
--
Bob Gailer
Chapel Hill NC
919-636-4239
More information about the Tutor
mailing list