[Tutor] Help :c
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Jan 15 18:29:44 EST 2021
On 15/01/2021 16:51, brayan torres wrote:
> Recall the readlines() method, which returns a list containing the lines of
> the file.
You don't need that advice its nearly always better just
to loop over the file object.
> Also, remember that all lines, except the last one, contain a \n at the
> end, which should not be included in the character count.
You seem to have ignored that bit of advice!
> I understand what I should do but my output is not the same as (S9 or
> A12)..
The S9 and A12 only apply to the 2 line example, not
to your actual data. But remember the advice about \n
above otherwise you will have the wrong results.
> This is my codeā¦
> file = open("/usercode/files/books.txt", "r")
>
> for i in file.readlines():
ignoring readlines() would give you
for line in file:
Which is preferred because you don't read the whole
file into memory at once. Faster and more memory
efficient.
Does the name line seem more like the thing you are
reading than i? Choosing useful names makes code much
easier to work with.
> print(i[0])
> print(len(i))
> my output is:
> H
> 13
> T
> 17
You need to print out more than just the letter and the length,
you need to combine them into a single string.
There are several ways to do that, probably the simplest
is string addition.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list