How can I remove (chomp) a trailing newline in Python?

什么是Perl的chomp函数的Python等价物,如果它是换行符,它将删除字符串的最后一个字符?


Try the method rstrip() (see doc Python 2 and Python 3)

>>> 'test stringn'.rstrip()
'test string'

Python's rstrip() method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp .

>>> 'test string n rnnr nn'.rstrip()
'test string'

To strip only newlines:

>>> 'test string n rnnr nn'.rstrip('n')
'test string n rnnr '

There are also the methods lstrip() and strip() :

>>> s = "   nrn  n  abc   def nrn  n  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def nrn  n  '
>>> s.rstrip()
'   nrn  n  abc   def'

我会说“pythonic”的方式来获取没有结尾换行符的行是splitlines()。

>>> text = "line 1nline 2rnline 3nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']

The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing r or n. Here are examples for Mac, Windows, and Unix EOL characters.

>>> 'Mac EOLr'.rstrip('rn')
'Mac EOL'
>>> 'Windows EOLrn'.rstrip('rn')
'Windows EOL'
>>> 'Unix EOLn'.rstrip('rn')
'Unix EOL'

Using 'rn' as the parameter to rstrip means that it will strip out any trailing combination of 'r' or 'n'. That's why it works in all three cases above.

This nuance matters in rare cases. For example, I once had to process a text file which contained an HL7 message. The HL7 standard requires a trailing 'r' as its EOL character. The Windows machine on which I was using this message had appended its own 'rn' EOL character. Therefore, the end of each line looked like 'rrn'. Using rstrip('rn') would have taken off the entire 'rrn' which is not what I wanted. In that case, I simply sliced off the last two characters instead.

Note that unlike Perl's chomp function, this will strip all specified characters at the end of the string, not just one:

>>> "Hellonnn".rstrip("n")
"Hello"
链接地址: http://www.djcxy.com/p/13518.html

上一篇: 为什么文本文件以换行符结束?

下一篇: 如何删除(chomp)Python中的尾随换行符?