What is the Python equivalent of Perl\'s chomp
function, which removes the last character of a string if it is a newline?
You may use line = line.rstrip('\n')
. This will strip all newlines from the end of the string, not just one.
Careful with "foo".rstrip(os.linesep)
: That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:
$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48)
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
>>>
Use "foo".rstrip("\r\n")
instead, as Mike says above.
I might use something like this:
import os
s = s.rstrip(os.linesep)
I think the problem with rstrip("\n")
is that you'll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use "\r\n"
). The other gotcha is that rstrip
will strip out repeated whitespace. Hopefully os.linesep
will contain the right characters. the above works for me.
rstrip doesn't do the same thing as chomp, on so many levels. Read http://perldoc.perl.org/functions/chomp.html and see that chomp is very complex indeed.
However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can.
Here you can see rstrip removing all the newlines:
>>> 'foo\n\n'.rstrip(os.linesep)
'foo'
A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this:
>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'