0
Is the "Book title" challenge from "python core" "Exceptions & Files" bugged?
I was told to provide the first letter of the book title and its length as its code. I first tried it, including whitespaces when providing length as its code but it didnt work then i tried it excluding whitespace only 2 solved. its very difficult to pick which book titles to be coded with whitespace or not maybe i m missing something any advice would be very helpful. """ #This the solution i presented file = open("/usercode/files/books.txt", "r") files=file.readlines() for i in files: bookcode=i[0]+(str(len(i.replace(" ","")))) print(bookcode) file.close() """ I apologise if i missed something.
2 Antworten
+ 4
readlines() will include the newline character '\n', that is at the end of all lines except the last line. Spaces should be counted in the length.
I.E.
"Harry Potter\n"
Will be a length of 12 with the newline character removed. Otherwise, you'll get 13, which is incorrect.
+ 4
As ChaoticDawg , already mentioned new lines will be included, so you might want to check whether this line contains new space..
Something like that:
file = open("/usercode/files/books.txt", "r")
#your code goes here
for line in file:
if line[-1] == "\n":
print(line[0] + str(len(line)-1))
else:
print(line[0] + str(len(line)))
file.close()