+ 1
How can i exclude "\n" from being counted by len(list()) in Python?
I am working in Python. I have booktitles in the file and my task is to print the first letter of the title and the length of the title. The "readlines" operation outputs every title in a separate line by "\n" and i do not know how to exclude this from being counted by "len()". This is what i have so far. file = open("/usercode/files/books.txt", "r") list = file.readlines() for line in list: print(line[0] + str(len(line))) file.close()
11 Answers
+ 2
use .strip()
https://www.sololearn.com/Discuss/2589736/?ref=app
+ 2
[Edited with bug fix]
The way I solved this is to use the string replace command like "string".replace("\n","") functionality.
Thus for your code:
file = open("/usercode/files/books.txt", "r")
list = file.readlines()
for line in list:
line = line.replace("\n","")
print(line + str(len(line)))
file.close()
Let me know if that helps!
+ 2
Magnus ,
the issue you are having is that the lines read from the file all (except the last one) have a trailing new-line sequence (\n), that also counts as a character.
this can be removed by using the string method strip(). it removes all leading and trailing whitespace (new-line sequences are considered as whitespace).
...
print(line[0] + str(len(line.strip())))
...
+ 2
Katya Ergieva ,
your hint does not work, did you try it before posting?
+ 2
Magnus ,
if you still have trouble with this exercise, please post the latest version of your code.
can you also post: tutorial name, exercise name / number
+ 1
Mangus, great catch, I edited it to remove two bugs, not saving result and a double dot.
0
Melba55 what do you mean? I gave the answer and I asked this question a year ago with lots of relevant help. What more do you need?
0
Thank you, Slick!
0
Hey jht,
i tried your version but that actually leaves me with the same mistake as before, that "len" still counts "\n".
0
Hi, you could do \\n and dont use quotations
0
Lothar, yes, and I think it even said it in a lesson in the Beginner Python course