0

I need help

I can't understand why my code is wrong You have been asked to make a special book categorization program, which assigns each book a special code based on its title. The code is equal to the first letter of the book, followed by the number of characters in the title. For example, for the book "Harry Potter", the code would be: H12, as it contains 12 characters (including the space). You are provided a books.txt file, which includes the book titles, each one written on a separate line. Read the title one by one and output the code for each book on a separate line. For example, if the books.txt file contains: Some book Another book Your program should output: S9 A12 My code file = open("/usercode/files/books.txt", "r") #ввеГите коГ ŃŃŽŠ“Š° spisok = file.readlines() for i in range (len(spisok)): a = list(spisok[i]) print (a[0] + str(len(a)-1)) file.close() Result Your output: H12 T16 P19 G17 Expected output: H12 T16 P19 G18

19th Oct 2021, 4:32 AM
Иван zirperger
Иван zirperger - avatar
3 Answers
+ 3
Hi! Read this once: "You are provided a books.txt file, which includes the book titles, each one written on a separate line". It means each book title is separated by a new line character but the last line doesn't have this. Inorder to handle this problem you can use an if-else statement to separate them. So, your code needs to be like this file = open("/usercode/files/books.txt", "r") #ввеГите коГ ŃŃŽŠ“Š° spisok = file.readlines() for i in range (len(spisok)): a = list(spisok[i]) if a[-1] == "\n": print (a[0] + str(len(a)-1)) else: print(a[0] + str(len(a))) file.close()
19th Oct 2021, 4:50 AM
Python Learner
Python Learner - avatar
+ 1
Ty I didn't think about it
19th Oct 2021, 4:52 AM
Иван zirperger
Иван zirperger - avatar
0
Ooooh
19th Oct 2021, 4:51 AM
Иван zirperger
Иван zirperger - avatar