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

"abc\n"  -->  "abc"

当前回答

我们通常会遇到三种类型的行尾:\n、\r\n和\r\n。re.sub中的一个相当简单的正则表达式,即r“\r?\n?$”,能够将它们全部捕获。

(我们必须抓住他们,对吗?)

import re

re.sub(r"\r?\n?$", "", the_text, 1)

在最后一个论点中,我们将替换的发生次数限制为一次,在某种程度上模仿了chomp。例子:

import re

text_1 = "hellothere\n\n\n"
text_2 = "hellothere\n\n\r"
text_3 = "hellothere\n\n\r\n"

a = re.sub(r"\r?\n?$", "", text_1, 1)
b = re.sub(r"\r?\n?$", "", text_2, 1)
c = re.sub(r"\r?\n?$", "", text_3, 1)

…其中a==b==c为True。

其他回答

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

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

我可能会用这样的方法:

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

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

我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。

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

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