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

"abc\n"  -->  "abc"

当前回答

import re

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

其他回答

对于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 ''
import re

r_unwanted = re.compile("[\n\t\r]")
r_unwanted.sub("", your_text)
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'
s = s.rstrip()

将删除字符串s末尾的所有换行符。需要赋值,因为rstrip返回一个新字符串,而不是修改原始字符串。

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