Strings in Python

MRAB google at mrabarnett.plus.com
Thu Feb 8 18:39:17 EST 2007


On Feb 8, 6:32 pm, attn.steven.... at gmail.com wrote:
> On Feb 8, 8:28 am, "Johny" <pyt... at hope.cz> 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?
>
> In this case, you can use:
>
> mystring = '12341'
> indices = [ _ for _ in range(len(mystring)) if mystring[_] == '1' ]
> print indices
>
Or:

mystring = '12341'
indices = [ i for i, c in enumerate(mystring) if c == '1' ]
print indices




More information about the Python-list mailing list