0

Counting the number of bytes in lines of a text file.

You are provided a books.txt file, which includes the book titles, each one written on a separate line. Read the title one by one and output the code for each book on a separate line.   For example, if the books.txt file contains: Some book Another book Your program should output: S9 A12 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. file = open("/usercode/files/books.txt", "r") #your code goes here for i in file:     m=len(i)     print("{0}{1}".format(i[0],m) file.close() I'm having troubles with the last line because as the last one doesn't have the '\n'. So, in that case my result is    S17 and the result has to be S18.

20th Apr 2021, 12:29 AM
Felipe Osorio
Felipe Osorio - avatar
1 Réponse
+ 3
Try using strip() on i before getting its len(). This will remove the '\n' from the string if present.
20th Apr 2021, 1:56 AM
ChaoticDawg
ChaoticDawg - avatar