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


Groups > comp.lang.python > #31494 > unrolled thread

Re: Index in a list

Started byChris Angelico <rosuav@gmail.com>
First post2012-10-17 21:23 +1100
Last post2012-10-17 21:23 +1100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#31494 — Re: Index in a list

FromChris Angelico <rosuav@gmail.com>
Date2012-10-17 21:23 +1100
SubjectRe: Index in a list
Message-ID<mailman.2339.1350469391.27098.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web