hackerman hackerman - 3 years ago 150
Python Question

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

I know I can use

.translate(None, string.punctuation)
to strip punctuation from a string. However, I'm wondering if there's a way to strip punctuation only if it it's the final character.

For example:
However, only strip the final punctuation.
->
However, only strip the final punctuation


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


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


I know I could write a while loop to do this but I'm wondering if there's a more elegant/efficient way.

Answer Source

You could simply use 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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download