Line indexing in Python
steve at holdenweb.com
Tue Dec 22 13:25:51 CET 2009
> seafoid wrote:
>> Hi Guys,
>> When python reads in a file, can lines be referred to via an index?
>> for line in file:
>> if line == '0':
>> This works, however, I am unsure if line 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,
> 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) )
those are brackets, not angle brackets
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/
More information about the Python-list