remove the last character or the newline character?

Duncan Booth duncan.booth at invalid.invalid
Thu Sep 28 10:30:51 EDT 2006


"Daniel Mark" <danielmarkhot at gmail.com> 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')



More information about the Python-list mailing list