仅当它是最后一个字符时如何去除标点符号

How to strip punctionation only if it's the last character

我知道我可以使用 .translate(None, string.punctuation) 从字符串中去除标点符号。但是,我想知道是否有一种方法可以仅在标点符号是最后一个字符时去除它。

例如: However, only strip the final punctuation. -> However, only strip the final punctuation

This is sentence one. This is sentence two! -> This is sentence one. This is sentence two

This sentence has three exclamation marks!!! -> This sentence has three exclamation marks

我知道我可以编写一个 while 循环来执行此操作,但我想知道是否有更多 elegant/efficient 方法。

您可以简单地使用 rstrip:

str.rstrip([chars])

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> import string

>>> s = 'This sentence has three exclamation marks!!!'
>>> s.rstrip(string.punctuation)
'This sentence has three exclamation marks'

>>> s = 'This is sentence one. This is sentence two!'
>>> s.rstrip(string.punctuation)
'This is sentence one. This is sentence two'

>>> s = 'However, only strip the final punctuation.'
>>> s.rstrip(string.punctuation)
'However, only strip the final punctuation'

re.sub(r'[,;\.\!]+$', '', 'hello. world!!!')