Book title project | Sololearn: Learn to code for FREE!

+4

Book title project

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

Marjaf

14 Answers

New Answer

+9

Or, 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"))))

+5

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

+4

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"))))

+3

Mr Myth thank you🙏

+2

_jakubwrz_ I seeeeeee😅😂 I forgot this...I wrote wrong readline instead readlines😐😅 And in else, I had to write -1 instead -2. It works.

+2

This will help you: https://code.sololearn.com/cPeBWF4tkD8w/?ref=app

+2

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

+1

Oh really? I tried it before i posted it, but I will try again

+1

Just change list=file.readline() to list=file.readlines()

+1

Also you can use .strip() for remove whitespace

+1

I tested the code again, it works for me... idk \n take only - 1

0

_jakubwrz_ Thank you but it doesn't work:(

-1

file = open("/usercode/files/books.txt", "r") #your code goes here books=file.readlines() for i in books: if i==books[-1]: value=len(i) else: value=len(i)-1 print(i[0]+str(value)) file.close()

-1

file = open("/usercode/files/books.txt", "r") for line in file: print(line[0]+str(len(line.strip("\n")))) file.close() You add .strip("\n") after line so it does not count \n as character when you are counting the length