Re: remove the last character or the newline character?



"Daniel Mark" <danielmarkhot@xxxxxxxxx> wrote:


In [2]: fileName = fileName[0:len(fileName)-1)] # remove the '\n'

To chop the last character regardless of what it is:

fileName = fileName[:-1]

You don't need the 0 since thats the default, and you can use a negative
index instead of subtracting from len(x).

Question two:
Does python provide any function that can remove the newline character
from a string if it exists?


To remove all trailing whitespace:

fileName = fileName.rstrip()

to just remove a newline:

fileName = fileName.rstrip('\n')
.