如果是最后一个通道,如何去除穿刺

2024-04-25 06:37:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我可以使用.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循环来实现这一点,但我想知道是否有一种更优雅/高效的方法。在


Tags: the方法gtonlyisthisonesentence
2条回答

您只需使用^{}

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!!!')

相关问题 更多 >