What is the Python equivalent of Perl\'s chomp
function, which removes the last character of a string if it is a newline?
It looks like there is not a perfect analog for perl's chomp. In particular, rstrip cannot handle multi-character newline delimiters like \r\n
. However, splitlines does as pointed out here.
Following my answer on a different question, you can combine join and splitlines to remove/replace all newlines from a string s
:
''.join(s.splitlines())
The following removes exactly one trailing newline (as chomp would, I believe). Passing True
as the keepends
argument to splitlines retain the delimiters. Then, splitlines is called again to remove the delimiters on just the last "line":
def chomp(s):
if len(s):
lines = s.splitlines(True)
last = lines.pop()
return ''.join(lines + last.splitlines())
else:
return ''