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

"abc\n"  -->  "abc"

当前回答

特殊情况的解决方案:

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

foobar= foobar[:-1]

剪切换行符。

其他回答

小心使用“foo”.rstrip(os.lineep):这只会在执行Python的平台上压缩换行符。例如,假设您在Linux下敲击Windows文件的行:

$ 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'
>>>

请改用“foo”.rstrip(“\r\n”),如Mike所述。

这将完全复制perl的chomp(减去数组上的行为)作为“\n”行终止符:

def chomp(x):
    if x.endswith("\r\n"): return x[:-2]
    if x.endswith("\n") or x.endswith("\r"): return x[:-1]
    return x

(注意:它不修改字符串“就地”;它不删除多余的尾随空格;考虑到\r\n)

尝试rstrip()方法(参见文档Python 2和Python 3)

>>> 'test string\n'.rstrip()
'test string'

Python的rstrip()方法在默认情况下去除了所有类型的尾随空格,而不是像Perl使用chomp那样只去除一行换行符。

>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'

要仅删除换行符,请执行以下操作:

>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '

除了rstrip(),还有strip()和lstrip()方法。下面是其中三个示例:

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

如果您的问题是清除多行str对象(oldstr)中的所有换行符,您可以根据分隔符“\n”将其拆分为一个列表,然后将此列表合并为一个新的str(newstr)。

newstr=“”.jjoin(oldstr.split('\n'))

特殊情况的解决方案:

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

foobar= foobar[:-1]

剪切换行符。