我知道我可以用.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循环来完成这个任务,但是我想知道是否有一种更优雅、更有效的方法。
发布于 2017-09-30 08:30:46
您可以简单地使用rstrip
str.rstrip([chars])
返回字符串的副本,并删除尾随字符。chars参数是一个字符串,指定要删除的字符集。如果省略或没有,chars参数默认为删除空格。chars参数不是后缀;相反,其值的所有组合都被删除:
>>> 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'
发布于 2017-09-30 09:16:15
re.sub(r'[,;\.\!]+$', '', 'hello. world!!!')
https://stackoverflow.com/questions/46504753
复制