如果字符串是换行符,我如何删除它的最后一个字符?

"abc\n"  -->  "abc"

当前回答

我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。

其他回答

我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。

import re

r_unwanted = re.compile("[\n\t\r]")
r_unwanted.sub("", your_text)

特殊情况的解决方案:

如果换行符是最后一个字符(大多数文件输入都是这样),那么对于集合中的任何元素,都可以按如下方式进行索引:

foobar= foobar[:-1]

剪切换行符。

>>> '   spacious   '.rstrip()
'   spacious'
>>> "AABAA".rstrip("A")
  'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
   ''
>>> "ABCABBA".rstrip("AB")
   'ABC'

包罗万象:

line = line.rstrip('\r|\n')