r0g wrote: > seafoid wrote: >> Hi Guys, >> >> When python reads in a file, can lines be referred to via an index? >> >> Example: >> >> for line in file: >> if line[0] == '0': >> a.write(line) >> >> This works, however, I am unsure if line[0] refers only to the first line or >> the first character in all lines. >> >> Is there an easy way to refer to a line with the first character being a >> single letter that you know? >> >> Thanks in advance, >> Seafoid. > > > If you want to know the index number of an item in a sequence you are > looping through (whether it be a file of lines or a list of characters, > whatever) use enumerate... > >>>> for index, value in enumerate("ABCD"): > print index, value > ... > 0 A > 1 B > 2 C > 3 D > > > If you want to extract an index number from the first part of of a given > line use split( split_character, maximum_splits_to_do ) and then angle > brackets to reference the first part (index 0)... > > >>>> a = "20 GOTO 10" >>>> int( a.split(' ',1)[0] ) > 20 > <nit> those are brackets, not angle brackets </nit>
regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ -- http://mail.python.org/mailman/listinfo/python-list