Line indexing in Python

r0g aioe.org at technicalbloke.com
Tue Dec 22 14:41:24 EST 2009


Steve Holden wrote:
> 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


<nit++>
They're actually square brackets, "brackets" on its own is more commonly
used as a synonym for parentheses (round brackets). But yes, I did get
that wrong in the above ;)
</nit++>

Cheers,

Roger :)



More information about the Python-list mailing list