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

"abc\n"  -->  "abc"

当前回答

对于perl的chomp,似乎没有完美的模拟。特别是,rstrip不能处理像\r\n这样的多字符换行符。然而,分裂线确实如这里所指出的那样。根据我对另一个问题的回答,您可以组合连接和拆分线来删除/替换字符串中的所有换行符:

''.join(s.splitlines())

下面只删除了一个尾随换行符(我相信chomp会这样做)。将True作为keeponds参数传递给拆分线将保留分隔符。然后,再次调用拆分线以删除最后一行上的分隔符:

def chomp(s):
    if len(s):
        lines = s.splitlines(True)
        last = lines.pop()
        return ''.join(lines + last.splitlines())
    else:
        return ''

其他回答

s = '''Hello  World \t\n\r\tHi There'''
# import the module string   
import string
# use the method translate to convert 
s.translate({ord(c): None for c in string.whitespace}
>>'HelloWorldHiThere'

使用正则表达式

s = '''  Hello  World 
\t\n\r\tHi '''
print(re.sub(r"\s+", "", s), sep='')  # \s matches all white spaces
>HelloWorldHi

替换\n,\t,\r

s.replace('\n', '').replace('\t','').replace('\r','')
>'  Hello  World Hi '

使用正则表达式

s = '''Hello  World \t\n\r\tHi There'''
regex = re.compile(r'[\n\r\t]')
regex.sub("", s)
>'Hello  World Hi There'

使用Join

s = '''Hello  World \t\n\r\tHi There'''
' '.join(s.split())
>'Hello  World Hi There'

我可以说,在没有换行符的情况下获取行的“pythonic”方法是splitlines()。

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

我可能会用这样的方法:

import os
s = s.rstrip(os.linesep)

我认为rstrip(“\n”)的问题是您可能需要确保行分隔符是可移植的。(一些过时的系统据说使用“\r\n”)。另一个陷阱是rstrip将去掉重复的空格。希望os.lineep包含正确的字符。以上这些对我很有用。

包罗万象:

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

小心使用“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所述。