Re: remove the last character or the newline character?



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

>>> fileName = 'Perfect Setup.txt\n'
>>> fileName.strip()
'Perfect Setup.txt'
>>>

Or you can use lstrip() or rstrip() to remove just the left or right side.

Just a caveat with the non-qualified strip/rstrip/lstrip...it will remove *all* whitespace, so if, for some reason, it's significant, and you only want to remove newlines, you have to specify it:

>>> s = ' some text \t\n'
>>> s.strip()
'some text'
>>> s.rstrip()
' some text'
>>> s.rstrip('\n')
' some text \t'

As the OP was talking about file-names, the use of initial/terminal spaces is allowable (albeit imprudent), depending on your platform, so one may or may not want to strip them off.

Fortunately, as in many other areas, Python offers the flexibility in an easy-to-use way, and comes with sensible defaults.

-tkc




.



Relevant Pages

  • Re: Stripping parts of a path
    ... I just ran into an issue with the rstrip method when using it on path ... If chars is given and not None, remove characters in chars instead. ... If you give chars to rstripit removes all those characters from the string not that substring. ...
    (comp.lang.python)
  • Re: strip part of string
    ... I found no way with Google mail to have plain text mail) ...     outp.write ... the string, including the '\n' at the end of the string/line, so a new ... His line-terminal '\n' has already disappeared before the rstrip gets ...
    (comp.lang.python)
  • Re: heredoc and variables
    ... Just for completeness, you can also use lstrip(), rstripand strip ... of a string, respectively. ... will get rid of the beginning newline. ... (and you want to preserve that indentation). ...
    (comp.lang.python)
  • Re: Maintaining leading zeros with the lstrip string function?
    ... function strips them leaving this as the result: ... How do I strip the path without losing the leading zeros in the file name? ... Use of the string module for lstrip and other ...
    (comp.lang.python)
  • Re: may be a bug in string.rstrip
    ... Scott SA a écrit: ... there is a bug in the rstrip, lstrip there isn't this problem. ...
    (comp.lang.python)