remove the last character or the newline character?
Tim Chase
python.list at tim.thechases.com
Thu Sep 28 10:40:40 EDT 2006
>> 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
More information about the Python-list
mailing list