我知道我可以使用@NgModule(...)
来删除字符串中的标点符号。但是,我想知道是否有一种方法可以删除标点符号,只要它是最后一个字符。
例如:
.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!!!
我知道我可以写一个while循环来做这个,但我想知道是否有更优雅/更有效的方法。
答案 0 :(得分:5)
您只需使用rstrip
:
str.rstrip([chars])
返回删除了尾随字符的字符串副本。 chars参数是一个字符串,指定要删除的字符集。如果省略或None,则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'
答案 1 :(得分:-1)
re.sub(r'[,;\.\!]+$', '', 'hello. world!!!')