+ 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()

18th Jul 2022, 8:17 AM
Magnus Behringer
11 Respuestas
18th Jul 2022, 9:08 AM
Slick
Slick - avatar
+ 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!
18th Jul 2022, 11:27 AM
jht
jht - avatar
+ 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()))) ...
18th Jul 2022, 1:52 PM
Lothar
Lothar - avatar
+ 2
Katya Ergieva , your hint does not work, did you try it before posting?
19th Jul 2022, 5:30 PM
Lothar
Lothar - avatar
+ 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
19th Jul 2022, 5:32 PM
Lothar
Lothar - avatar
+ 1
Mangus, great catch, I edited it to remove two bugs, not saving result and a double dot.
18th Jul 2022, 7:19 PM
jht
jht - avatar
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?
18th Jul 2022, 9:57 AM
Slick
Slick - avatar
0
Thank you, Slick!
18th Jul 2022, 10:56 AM
Magnus Behringer
0
Hey jht, i tried your version but that actually leaves me with the same mistake as before, that "len" still counts "\n".
18th Jul 2022, 4:16 PM
Magnus Behringer
0
Hi, you could do \\n and dont use quotations
19th Jul 2022, 1:10 PM
Katya Ergieva
Katya Ergieva - avatar
0
Lothar, yes, and I think it even said it in a lesson in the Beginner Python course
19th Jul 2022, 5:43 PM
Katya Ergieva
Katya Ergieva - avatar