+ 1

Why doesn’t my code work?

Python core, problem 51, for so reason it works, yet the last line doesn’t. Code: file = open("/usercode/files/books.txt", "r") list = file.readlines() listlen = len(list) items = "" for i in list: itemlen = len(i) - 1 item = i[0] items += str(item)+str(itemlen)+"\n" file.close() print (items)

20th Jun 2022, 7:49 PM
Gabriel Burchfield
3 ответов
+ 2
You have not handled the info in the yellow box Recall the readlines() method, which returns a list containing the lines of the file. Also, remember that all lines, except the last one, contain a \n at the end, which should not be included in the character count.
20th Jun 2022, 9:34 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Gabriel Only the last item in the list will contain the correct length, all other items in the list have '\n' appended, which is counted as a character. So you must write a code which can identify the difference between all items except the last item.
21st Jun 2022, 2:16 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
Rik Wittkopp 1) thank you! 2) thank you but thats not my question, the books ate all one ahead, considering the method of counting python uses, but the last book is the nirmal length, so when I subtract from the variable itemlen, I get it wrong
20th Jun 2022, 9:43 PM
Gabriel Burchfield