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

"abc\n"  -->  "abc"

当前回答

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'

其他回答

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

import re

r_unwanted = re.compile("[\n\t\r]")
r_unwanted.sub("", your_text)
>>> '   spacious   '.rstrip()
'   spacious'
>>> "AABAA".rstrip("A")
  'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
   ''
>>> "ABCABBA".rstrip("AB")
   'ABC'

这将适用于windows和linux(如果您只寻找重新解决方案,那么使用re-sub有点贵)

import re 
if re.search("(\\r|)\\n$", line):
    line = re.sub("(\\r|)\\n$", "", line)

我正在从我之前在另一个答案的评论中发布的一个基于正则表达式的答案中冒泡出来。我认为使用re比str.rstrip更明确地解决这个问题。

>>> import re

如果要删除一个或多个尾随换行符:

>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'

如果要删除所有换行符(而不仅仅是尾部):

>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'

如果只想删除1-2个尾随换行符(即,\r,\n,\r\n,\n\r,\r,\r\n\r\n)

>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')
'\nx'

我有一种感觉,大多数人在这里真正想要的是只删除一个尾随换行符,\r\n或\r\n,而不是更多。

>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
'\nx\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
'\nx\r\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
'\nx'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)
'\nx'

(?:是创建一个非捕获组。)

(顺便说一句,这不是“…”.rstrip(“\n”,“”).rstrap(“\r”,“)所做的,其他人可能不清楚这一点。str.rstrip删除尽可能多的尾随字符,因此像foo这样的字符串将导致foo为假阳性,而您可能希望在删除单个尾随字符后保留其他换行符。)