+ 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()
9 Antworten
+ 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.
+ 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 🤷♂️
+ 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"?
+ 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.
+ 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
+ 3
Eacy Did you solve python book library training?
+ 3
Oh my god. Thank you Lothar.
+ 2
Eacy: There is an empty line at the end of my output, so it doesn't match the expected one
- 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()