Strings in Python

Gary Herron gherron at islandtraining.com
Thu Feb 8 11:39:36 EST 2007


Johny wrote:
> Playing a little more with strings, I found out that string.find
> function provides the position of
> the first occurance of the substring in the string.
> Is there a way how to find out all substring's position ?
> To explain more,
> let's suppose
>
> mystring='12341'
> import string
>
>   
>>>> string.find(mystring ,'1')
>>>>         
> 0
>
> But I need to find the  possition the other '1' in mystring too.
> Is it possible?
> Or must I use regex?
> Thanks for help
> L
>
>   
You could use a regular expression.  The re module has s function 
"findall" that does what you want.

Also, if you read the documentation for strings find method, you'll find:

1 S.find(sub [,start [,end]]) -> int
2
3 Return the lowest index in S where substring sub is found,
4 such that sub is contained within s[start,end].  Optional
5 arguments start and end are interpreted as in slice notation.
6
7 Return -1 on failure.

So put your find in a loop, starting the search one past the previously 
found occurrence.

  i = string.find(mystring, i+1)

Gary Herron





More information about the Python-list mailing list