+ 1

Please solve the following question

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

19th Apr 2022, 6:20 AM
Amidu Yohan
Amidu Yohan - avatar
8 Answers
+ 5
Amidu Yohan the issue with this exercise is, that the lines we have to read from the file have ALL (!!! except the last one !!!) a trailing new-line sequence (\n). so using some arithmetic operations to handle this, will not give a correct result. the pythonic way of solving this task is to use the string method .rstrip(), which will remove all white-space characters at the end of a string. since new-line sequences are also considered as white-space characters, this way will work. this your code slightly fixed: file = open("/usercode/files/books.txt", "r") while True: t = file.readline() L = list(t) if len(t) == 0: break else: print(f"{L[0]}{(len(t.rstrip()))}") # used f-string to create the output string // used t.rstrip() to remove new-line sequences file.close()
19th Apr 2022, 2:50 PM
Lothar
Lothar - avatar
+ 1
print(L[0]+str(len(t)-1))
19th Apr 2022, 6:51 AM
Oma Falk
Oma Falk - avatar
+ 1
https://code.sololearn.com/cnR5VYOKlV4s/?ref=app
21st Apr 2022, 3:45 AM
mohammed shibli
mohammed shibli - avatar
0
file = open("/usercode/files/books.txt", "r") #your code goes here while True: t = file.readline() L = list(t) if len(t) == 0: break else: print(L[0],(len(t)-1)) file.close()
19th Apr 2022, 6:21 AM
Amidu Yohan
Amidu Yohan - avatar
0
Can anyone tell whether my phython code is true? Jay Matthews
19th Apr 2022, 6:44 AM
Amidu Yohan
Amidu Yohan - avatar
0
file = open("/usercode/files/books.txt", "r") for line in file.readlines(): print("\n" + line[0] + str(len(line))) file.close
19th Apr 2022, 8:14 AM
Š Š¾Š¼Š°Ń€Šø
Š Š¾Š¼Š°Ń€Šø  - avatar
0
Loveit=("Comments") print (Loveit) print ("I \nlove \nProgramming\n!") print ("Share\nand\ndrink\nLatte") print ("Vaccinated") print ("Please get the vaccine as fast as you can") negative=("negative") print ("Fast test "+negative) PunchBag=(" ") print ("Punch Bag"+PunchBag) print ("Bye Bye") ?
21st Apr 2022, 6:10 AM
Javlonbek Hojiraximov
Javlonbek Hojiraximov - avatar