Hi.iam learning Python recently.can anyone tell me what the problem is with this code?:( file = open("/usercode/files/books.txt", "r") list=file.readline() for i in list: if i==list[len(list)-1]: title=i[0]+str(len(i)) print(title) else: title=i[0]+str(len(i)-2) print(title) file.close()
1/15/2021 6:30:23 PM
Marjaf12 Answers
New AnswerOr, instead of checking whether there is a "\n" at the end of each line, you could just get rid of them 😉 with open("/usercode/files/books.txt") as file: for line in file: print(line[0] + str(len(line.strip("\n"))))
Or just 3 lines with open("/usercode/files/books.txt") as file: for title in file.readlines(): print(title[0] + str(len(title.strip("\n"))))
file = open("/usercode/files/books.txt", "r") list=file.readlines() for line in list : if "\n" in line: print(line[0]+str(len(line)-1)) else: print(line[0]+str(len(line))) file.close() This should work In the first if you replace it with an if \n in i: (you search if there is a new line) Then in the next line (title=i[0]...) you need to subract 1 from the number of charcters because else it would count \n And in the else: you don't need that - 2 The rest should be fine Hope it's helpfull
_jakubwrz_ I seeeeeee😅😂 I forgot this...I wrote wrong readline instead readlines😐😅 And in else, I had to write -1 instead -2. It works.
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
SoloLearn Inc.
4 Embarcadero Center, Suite 1455Send us a message