Index in a list

Anatoli Hristov tolidtm at gmail.com
Wed Oct 17 08:38:52 EDT 2012


Thanks a lot this solved my issue:)

Regards

Anatoli

On Wed, Oct 17, 2012 at 12:23 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, Oct 17, 2012 at 9:10 PM, Anatoli Hristov <tolidtm at gmail.com> wrote:
>> Hello,
>>
>> I'm trying to index a text in a list as I'm importing a log file and
>> each line is a list.
>>
>> What I'm trying to do is find the right line which contains the text
>> User : and take the username right after the text "User :", but the
>> list.index("(User :") is indexing only if all the text matching. How
>> can I have the right position of the line which contains the word
>> ("(User :")
>
> What you want is a search. Try this:
>
> for idx,val in enumerate(list):
>     # if "(User:" in val: break
>     # if val.startswith("(User:"): break
>
>
> Pick one or t'other of those conditions; the first one looks for any
> string _containing_ "(User:", while the second will match specifically
> on the beginning.
>
> After this loop, list[idx] is the "User" line, and the entry after it
> is in list[idx+1] - but be aware that you'll get an exception if
> list[idx] is the last entry in the list.
>
> By the way, it's generally considered dodgy to use the name "list" for
> a list - it stops you from using the list constructor. I'd recommend
> calling it "lst" instead or, better, to name it according to what it
> contains (eg if it's a list of log entries, call it 'log_entries' or
> something).
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list