0

What's wrong with this code?

It works properly except for the last title file = open("/usercode/files/books.txt", "r") def Title_Program(file): for line in file: Title_C = len(line)-1 for x in line: if x == "n": print (line[0]+str(Title_C)) elif x != "n": print(line[0]+str(len(line))) break Title_Program(file) file.close()

19th Oct 2020, 9:27 PM
Micah Arce
Micah Arce - avatar
3 Answers
+ 1
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
29th Dec 2020, 6:29 PM
Lam Wei Li
Lam Wei Li - avatar
0
Micah Arce Your for loop is useless cause you are breaking immediately after reading the first character, so it doesn't iterate over the whole line, just remove it and replace the x == "n" with line[0] == "n"
20th Oct 2020, 2:55 AM
QTWizard
0
file = open("/usercode/files/books.txt","r").readlines() for line in file: line = line.rstrip("\n") print(line[0] + str(len(line)))
28th Oct 2020, 8:10 AM
Taral Patel
Taral Patel - avatar