+ 2

Why is my code being marked as incorrect in Python 3 project book titles

Below is my code for the project and it appears to give the correct answers but is shown as being wrong and I don't understand. Can anyone help with this. file = open("/usercode/files/books.txt", "r") #your code goes here for line in file: x = str(line[0]) y = str(len(line) - 1) print(x+y) file.close()

22nd Oct 2020, 8:44 AM
Sam Sackerson
Sam Sackerson - avatar
4 odpowiedzi
+ 3
Sam Sackerson , the issue in this exercise is, that reading from a txt file in python the returned string always contains a new-line (/n) squence at the end of the line (except of the last line). Your code tries to eliminate that new-line sequence. You should use instead a string method, which can do this more accurate. rstrip() is used to remove all whitespaces at the end of the line. you can include this line as first statement in the for loop: for ... line = line.rstrip() ...
22nd Oct 2020, 12:41 PM
Lothar
Lothar - avatar
+ 2
Last line doesn't include '\n'
22nd Oct 2020, 9:51 AM
Julia Shabanova
Julia Shabanova - avatar
+ 1
A simpler way with 5 lines of code. A simple explanation, loop through all lines, and if a line has trailing/ending "\n" remove it from the count of the length. https://code.sololearn.com/cdaPdMWWeN3W/?ref=app
15th Dec 2020, 6:41 PM
Lam Wei Li
Lam Wei Li - avatar
0
If you could provide the prompt of the problem, it would be better to understand what you wanted to be done. I have understood from the code above that you're trying to print the first char of each line with the length of the remaining line without the first char.
22nd Oct 2020, 9:22 AM
QTWizard