+ 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()
9 Answers
+ 3
https://code.sololearn.com/cPeBWF4tkD8w/?ref=app
Here is the solution to the bookâs task, which can be analysed đ if you like.
+ 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.
+ 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().
+ 4
In the last element of list all characters count.
+ 2
https://code.sololearn.com/cXZK6nWRjVTm/?ref=app
Made my own and extremely thorough variation for the absolute rookies like I am đ
+ 1
Lothar , the thing is that the last line of any such file may not include this "/n" thingie. I missed that aspect.
+ 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.
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?
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()