\n essentially means "create another line"
So, when you deleted all lines \n , there is still the previous line
the lines below me should be gone\n
Which again means βcreate another lineβ, beyond the ones you have already deleted
Since you say you cannot use rstrip , you can end the loop with
file_out[-1] = file_out[-1].strip('\n')
remove \n from the last item. Since \n cannot exist anywhere on the line, rstrip and strip will have the same effect
Or without any strip or endswith :
if file_out[-1][-1] == '\n': file_out[-1] = file_out[-1][:-1]
Note that \n is a single character, serial number 0x0a as hexadecimal, not two characters \ and n , ordinals 0x5c and 0x6e . That's why we use -1 , not -2
mhlester
source share