+ 3

Book Titles python training

I've tried to solve it but my code outputes one more line than expected : file = open("/usercode/files/books.txt", "r") library = file.readlines() a = 0 for i in library: book = library[a] a = a + 1 first = book[0] second = len(book) print(str(first) + str(second - 1)) file.close()

31st Oct 2020, 6:31 AM
Mohammad Hosein Nosrati
Mohammad Hosein Nosrati - avatar
9 odpowiedzi
+ 12
Mohammad Hosein Nosrati , there is no empty line in your output, the problem is something else. Have a look at the data that comes from the file by your code: Harry Potter\n' --> H12 'The Hunger Games\n' --> T16 'Pride and Prejudice\n' --> P19 'Gone with the Wind' --> G17 As you can see, all lines except the last one does have a trailing new-line sequence. This will be removed by your code, so also in the last line (here it removes a real character). The result is not correct for the last line. Its stated as 17, but should be 18.
31st Oct 2020, 12:00 PM
Lothar
Lothar - avatar
+ 7
Mohammad Hosein Nosrati Oh, then i don't know how to fix. You could try f string or format output like: print(f"{str(first)}{str(second-1)}) but if this doesn't work 🤷‍♂️
31st Oct 2020, 11:47 AM
🔥EACY🔥
🔥EACY🔥 - avatar
+ 6
Whats the problem? If I execute the code it prints all the books with first letter and length. What do you mean with "outputs one more line than expected"?
31st Oct 2020, 11:24 AM
🔥EACY🔥
🔥EACY🔥 - avatar
+ 6
Harel , But you can't be serious now? what you are suggesting is a hard coding to get this exercise passed. we are here in a learning platform, and it is is our main goal to learn programming languages, not to earn some xp's. can you please tell me why are you here in this place? if you want to be successful in in whatever you are doing, you have to face challenges coming ahead by solving them and also change your behavior.
5th Jan 2021, 12:56 PM
Lothar
Lothar - avatar
+ 5
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:38 PM
Lam Wei Li
Lam Wei Li - avatar
+ 3
Eacy Did you solve python book library training?
31st Oct 2020, 11:48 AM
Mohammad Hosein Nosrati
Mohammad Hosein Nosrati - avatar
+ 3
Oh my god. Thank you Lothar.
31st Oct 2020, 6:05 PM
Mohammad Hosein Nosrati
Mohammad Hosein Nosrati - avatar
+ 2
Eacy: There is an empty line at the end of my output, so it doesn't match the expected one
31st Oct 2020, 11:28 AM
Mohammad Hosein Nosrati
Mohammad Hosein Nosrati - avatar
- 1
Try this: file = open("/usercode/files/books.txt", "r") #your code goes here for line in file: first = line[0] length = str(len(line)-1) lengthy = str(len(line)) if line[-1] == "\n": print(first+length) else: print(first+lengthy) file.close()
27th Jul 2022, 5:53 AM
Nikhilesh Tayal