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

"abc\n"  -->  "abc"

当前回答

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

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

其他回答

我正在从我之前在另一个答案的评论中发布的一个基于正则表达式的答案中冒泡出来。我认为使用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为假阳性,而您可能希望在删除单个尾随字符后保留其他换行符。)

包罗万象:

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所述。

您可以使用strip:

line = line.strip()

演示:

>>> "\n\n hello world \n\n".strip()
'hello world'
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'