Line indexing in Python
Steve Holden
steve at holdenweb.com
Fri Dec 18 11:12:08 EST 2009
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.
>
Each time around the loop the variable "line" contains the current line
from the file. Thus line[0] is the first character of the current line.
If your intent is to print all lines beginning with "0" then your code
will work.
> Is there an easy way to refer to a line with the first character being a
> single letter that you know?
>
You might express it more readably as
for line in file:
if line.startswith("0"):
a.write(line)
This seems to express the intent of your code somewhat more directly.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list