remove the last character or the newline character?

Georg Brandl g.brandl-nospam at gmx.net
Thu Sep 28 10:23:05 EDT 2006


Daniel Mark wrote:
> Hello all:
> 
> I have the following snippet:
> 
> In [1]: fileName = 'Perfect Setup.txt\n'
> In [2]: fileName = fileName[0:len(fileName)-1)]   # remove the '\n'
> character
> In [3]: fileName
> Out[3]: 'Perfect Setup.txt'
> 
> Question one:
> Does python provide any function that can remove the last character of
> a string?
> I don't know whether or not the method I used is efficient

fileName = fileName[:-1]

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

fileName = fileName.rstrip("\n")

though this will remove more than one newline if present. If you only want
to remove one newline, use

if fileName[-1:] == '\n':
     fileName = fileName[:-1]

Georg



More information about the Python-list mailing list