Is there a string function that will tell me...

Steve Purcell stephen_purcell at yahoo.com
Thu Apr 19 11:47:07 EDT 2001


Terrence Spencer wrote:
> In the Foxpro language the is a function called:
> 
>     AT(SearchingFor,StringToSearch,Count)
> 
> So if I want to find out what location the 3rd "e" is in the string
> "terrence" I would say:
> 
> ?at("e","terrence",3)
> 
> and that would return 7, the location of the 3rd "e".

To find the first, use the standard function string.find :-

    >>> import string
    >>> s = "Municipal Advisory Council of Texas"
    >>> string.find(s, "Texas")
    30
    >>> 

To find the nth occurrence, roll your own function :-

    >>> def findnth(s, substr, count):
    ...   pos = -1
    ...   for i in xrange(count):
    ...     pos = string.find(s, substr, pos+1)
    ...     if pos == -1: break
    ...   return pos
    ... 
    >>> findnth(s, 'i', 3)
    13
    >>> 
    >>> findnth("terrence", "e", 3)
    7

-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list