0

Reading lines in different ways, why different results?

Yesterday evening I almost resolved the module test about reading a file "Book Titles" if not for a little differences, all but the last line had a +1 lenght. Either that I tried with readlines() or readline(). This morning after further attempts I finally succeeded with the use of read() and splitlines() Why, even if I replaced the \n it keep repeating that further character/new line? And how could that be prevented by still using 'readlines(s)' ? https://code.sololearn.com/ca2357A23A13 PS: is it good at it seems to not even use any 'readline(s)' or there are any drawbacks ?

22nd Mar 2021, 7:28 PM
tebkanlo
tebkanlo - avatar
6 Réponses
+ 2
tebkanlo with the correct escape you get same result for each cases: https://code.sololearn.com/cOGMgTiGh6gW/?ref=app
22nd Mar 2021, 9:38 PM
visph
visph - avatar
+ 2
because "\\n" is different from "\n"... later is escape code for new line, while former is escape code of backslash followed by 'n'... in other words, "\\n" equals the raw string: r"\n" not the new line char ;)
22nd Mar 2021, 7:36 PM
visph
visph - avatar
+ 2
no: by putting "\\" you make escape the "\" itself... as there's no raw "\" in the target string, you leave it unchanged, with it's new line "\n" char at the end, wich count as a char in the length of string, even it's not a 'visible' character appart by starting a new line...
22nd Mar 2021, 8:24 PM
visph
visph - avatar
+ 2
visph ooh. Ok. Now I understand! Sorry, I am not a native speaker, so I had to re read it with a clear mind now to get it. Thanks
23rd Mar 2021, 9:24 PM
tebkanlo
tebkanlo - avatar
+ 1
@visph I know about escaping the special character \, here I simply wrote it in a natural way, while in the given code, even if replaced correctly with >>> line = line.replace("\\n", "") the outcome is still wrong. I suppose because of how readline(s) handle the job
22nd Mar 2021, 7:58 PM
tebkanlo
tebkanlo - avatar
0
Thanks, but anyway the point of this question is not that, even with the correct escaped the results are different In this example code the line in the opened file is "Harry Potter" but the len() for that line is 13 instead of 12 https://code.sololearn.com/ca2357A23A13
22nd Mar 2021, 9:32 PM
tebkanlo
tebkanlo - avatar