如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"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'
其他回答
特殊情况的解决方案:
如果换行符是最后一个字符(大多数文件输入都是这样),那么对于集合中的任何元素,都可以按如下方式进行索引:
foobar= foobar[:-1]
剪切换行符。
只需使用:
line = line.rstrip("\n")
or
line = line.strip("\n")
你不需要这些复杂的东西
我们通常会遇到三种类型的行尾:\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。
尝试rstrip()方法(参见文档Python 2和Python 3)
>>> 'test string\n'.rstrip()
'test string'
Python的rstrip()方法在默认情况下去除了所有类型的尾随空格,而不是像Perl使用chomp那样只去除一行换行符。
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
要仅删除换行符,请执行以下操作:
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
除了rstrip(),还有strip()和lstrip()方法。下面是其中三个示例:
>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
在很多层面上,rstrip做的事情与chomp不同。阅读http://perldoc.perl.org/functions/chomp.html看到chomp确实非常复杂。
然而,我的主要观点是chomp最多删除1行结尾,而rstrip将删除尽可能多的结尾。
在这里,您可以看到rstrip删除了所有换行符:
>>> 'foo\n\n'.rstrip(os.linesep)
'foo'
使用re.sub可以更接近典型的Perl chomp用法,如下所示:
>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'