+ 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

4th Dec 2022, 1:54 PM
Alex Madsen
8 Antworten
+ 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', '')
4th Dec 2022, 2:21 PM
Jayakrishna 🇼🇳
+ 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.
4th Dec 2022, 2:08 PM
Jayakrishna 🇼🇳
+ 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.
4th Dec 2022, 3:38 PM
Jayakrishna 🇼🇳
+ 1
And how would I go about doing that? I can’t just say len-1, since the last book doesn’t have \n
4th Dec 2022, 2:14 PM
Alex Madsen
+ 1
Thank you!
4th Dec 2022, 2:29 PM
Alex Madsen
+ 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()))
4th Dec 2022, 2:35 PM
Bob_Li
Bob_Li - avatar
+ 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 ?
4th Dec 2022, 3:06 PM
Alex Madsen
+ 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=""
4th Dec 2022, 3:31 PM
Bob_Li
Bob_Li - avatar