+ 2

How do I fix this code?

This is from a code exercise here on Sololearn under File Handling. It's supposed to: 1. Open and read a file containing a list of book titles. 2. Assign each book a special code based on the book title and number of characters (including spaces). Eg: Harry Potter would be assigned H12. 3. Close the file. https://code.sololearn.com/cMP0zlyHV9i0/?ref=app

10th Sep 2022, 1:49 AM
Kamdili Ife Darachukwu
Kamdili Ife Darachukwu - avatar
5 Answers
+ 2
You probably don't have to set it to uppercase. Here's a quick breakdown. file = open("/usercode/files/books.txt", "r") # A lot is wrong with this code block #is for user input not file input #book_title0 = input([]) #book_title1 = book_title0.upper() #print(book_title1[0], len(book_title1)) for line in file.readlines(): print(line) print(line[0]) #minus the newline character #might have been thinking of another language been doing a few refreshers. print(str(len(line)-1)) print(line[0]+str(len(line)-1)) #so yeah direct replace fixes that. # print(str(len(line.replace("/n","")))) #print(line[0]+str(len(line.replace("/n","")))) file.close()
10th Sep 2022, 2:00 AM
morl
morl - avatar
+ 8
Remember to only output exactly what was asked for by the task. Additional and unnecessary outputs will fail you because you are considered not following the instructions.
10th Sep 2022, 2:17 AM
Ipang
+ 5
morl , are you aware that the last line of a text file does not contain a `new-line` character? if not, the length of the last line will not be calculated properly.
10th Sep 2022, 12:33 PM
Lothar
Lothar - avatar
+ 5
Kamdili Ife Darachukwu , what you can do is to use `rstrip()` method. this will remove all trailing whitespaces from a string. `new-line sequence` is also removed. apply it to each line you are reading from the file.
11th Sep 2022, 6:32 AM
Lothar
Lothar - avatar
+ 1
morl That explains a lot. I already got it to work but the last line is one character short. Any ideas on how I could fix that? Thank you.
11th Sep 2022, 12:53 AM
Kamdili Ife Darachukwu
Kamdili Ife Darachukwu - avatar