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

"abc\n"  -->  "abc"

当前回答

只需使用:

line = line.rstrip("\n")

or

line = line.strip("\n")

你不需要这些复杂的东西

其他回答

在很多层面上,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'
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 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'

或者你可以用regexp变得更古怪

注意,rstrip的行为与Perl的chomp()不同,因为它不会修改字符串。也就是说,在Perl中:

$x="a\n";

chomp $x

结果$x为“a”。

但在Python中:

x="a\n"

x.rstrip()

将意味着x的值仍然是“a \n”。即使x=x.rstrip()也不总是给出相同的结果,因为它会从字符串末尾删除所有空格,而不是最多一个换行符。