Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #31494

Re: Index in a list

References <CAKhY55P2-9GJtj_sZCPdJb2R00OZ3GXjZVixuDasn_Cisb_+yw@mail.gmail.com>
Date 2012-10-17 21:23 +1100
Subject Re: Index in a list
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2339.1350469391.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Oct 17, 2012 at 9:10 PM, Anatoli Hristov <tolidtm@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Index in a list Chris Angelico <rosuav@gmail.com> - 2012-10-17 21:23 +1100

csiph-web