Re: Index in a list

Discussion in 'Python' started by Chris Angelico, Oct 17, 2012.

  1. On Wed, Oct 17, 2012 at 9:10 PM, Anatoli Hristov <> 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
    Chris Angelico, Oct 17, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. karthikeyavenkat
    Replies:
    2
    Views:
    566
    Bryce
    Mar 17, 2005
  2. Shawn W_
    Replies:
    5
    Views:
    264
    Aldric Giacomoni
    Sep 16, 2009
  3. ngoc
    Replies:
    5
    Views:
    167
    Tad McClellan
    May 11, 2006
  4. Tomasz Chmielewski

    sorting index-15, index-9, index-110 "the human way"?

    Tomasz Chmielewski, Mar 4, 2008, in forum: Perl Misc
    Replies:
    4
    Views:
    269
    Tomasz Chmielewski
    Mar 4, 2008
  5. Stefan Mueller
    Replies:
    7
    Views:
    176
    Thomas 'PointedEars' Lahn
    Nov 28, 2005
Loading...

Share This Page