[Tutor] position of an element in list:

Mark Lawrence breamoreboy at yahoo.co.uk
Fri Jul 23 18:51:17 CEST 2010


On 23/07/2010 16:43, Steven D'Aprano wrote:
> On Fri, 23 Jul 2010 11:22:54 pm Vineeth Rakesh wrote:
>> Hello all,
>>
>> How to return the position of a character in a string. Say I have
>> str1 = "welcome to the world" if i want to return the position of the
>> first occurrence of "o" how to do it?
>
> str1.find("o") will return the index of the first "o", or -1 if not
> found.
>
> str1.rfind("o") does the same, but searches from the right instead of
> the left.
>
> str1.index("o") is like find, but it raises an exception instead of
> returning -1. Naturally there is a rindex as well.
>

For the OP and possibly others, all of these methods have optional start 
and end arguments.  Help for find shows:-

find(...)
     S.find(sub [,start [,end]]) -> int

     Return the lowest index in S where substring sub is found,
     such that sub is contained within s[start:end].  Optional
     arguments start and end are interpreted as in slice notation.

     Return -1 on failure.

Mark Lawrence




More information about the Tutor mailing list