+ 1
Why am I getting the wrong output? [Fixed]
Categorise books in file, do this by title and length of title. Fx. ‘Harry Potter’ = H12, (including space) ————————————————— file = open("/usercode/files/books.txt", "r") for book in file: print(book[0]+str(len(book))) file.close() ————————————————— Why does most len come out +1, but not all? My Output: H13, T17, P20, G18 Expected Output: H12, T16, P19, G18
8 ответов
+ 2
You can do like :
if '\n' in book :
Or book.count('\n') > 0: len-1. Else len
Otherwise book.strip() removes leading, trailing spaces or new character from book. Then count len()
Or use replace method :
book.replace('\n', '')
+ 2
All lines except last line have \n character at end. len() counts that too. So remove the \n and count.
Or don't calculate \n into.
+ 2
You are calculating and printing result.
You are not removing print function appending \n. These 2 are different. each print adds \n by its end='\n' parameter.
+ 1
And how would I go about doing that?
I can’t just say len-1, since the last book doesn’t have \n
+ 1
Thank you!
+ 1
use string.strip() to remove leading and trailing whitespace, as well as terminating newlines.
for book in file:
print(book[0]+str(len(book.strip()))
+ 1
The .strip() method worked.
However, i am a bit confused after the fact.
If i stripped all \n, by saying;
book = book.strip()
why did it still print each output on a seperate line? Should the output not have been;
H12T16P19G18
?
+ 1
you only applied the strip when computing the length. The original string was unchanged.
yes, you would have to reassign the book value to alter it.
print adds it's own newline. unless you use end=""