+ 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()
4 ответов
+ 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()
...
+ 2
Last line doesn't include '\n'
+ 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
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.