+ 6

I can't pass the "book names" exercise in the "exceptions and files" section for Python 3. What I am doing wrong?

file = open("/usercode/files/books.txt", "r") lines=file.readlines() for line in lines: first_letter=line[0] total_letters=len(line)-1 result=first_letter+str(total_letters) print(result) file.close()

17th Oct 2020, 6:03 PM
Dimitry Buylin
Dimitry Buylin - avatar
9 ответов
+ 3
https://code.sololearn.com/cPeBWF4tkD8w/?ref=app Here is the solution to the book‘s task, which can be analysed 👆 if you like.
17th Oct 2020, 6:10 PM
JaScript
JaScript - avatar
+ 12
Dimitry , the reason of your troubld seems to be the fact, that reading from file is also containing the new lind sequence "\n". As this also counts as character when checking the length, you have to strip it off from all lines.
17th Oct 2020, 7:50 PM
Lothar
Lothar - avatar
+ 9
The best way to remove all kind of whitespaces ("\n" is one of several whitespace sequences) when reading from a file is to use the string method strip() or rstrip().
18th Oct 2020, 9:32 AM
Lothar
Lothar - avatar
+ 4
In the last element of list all characters count.
17th Oct 2020, 6:23 PM
Oma Falk
Oma Falk - avatar
+ 2
https://code.sololearn.com/cXZK6nWRjVTm/?ref=app Made my own and extremely thorough variation for the absolute rookies like I am 😆
18th Oct 2020, 12:14 AM
Dimitry Buylin
Dimitry Buylin - avatar
+ 1
Lothar , the thing is that the last line of any such file may not include this "/n" thingie. I missed that aspect.
17th Oct 2020, 10:46 PM
Dimitry Buylin
Dimitry Buylin - avatar
+ 1
Shiki congratulation. In the line 7 - 13 I follow simply in the task description described input data and prepare it, means to each line of data the „\n“ will be added. And when the data‘s input ends, it will be in line 12 from the data last line the „\n“ removed. Happy coding.
18th Oct 2020, 9:16 AM
JaScript
JaScript - avatar
0
JaScript , man, thank u! Though I felt myself quite stupid whilst getting through ur code :D could u pls also explain the meaning of the line 12 there?
17th Oct 2020, 10:49 PM
Dimitry Buylin
Dimitry Buylin - avatar
0
file = open("/usercode/files/books.txt", "r") filelines=[] for lines in file: filelines.append(lines.strip()) for i in filelines: print(i[0]+str(len(i))) file.close()
20th Jun 2022, 10:29 AM
Abishake Mounasamy
Abishake Mounasamy - avatar