Remove punctuations from the end of a string (and not from the middle)

Viewed 33

How can I get rid of the punctuations only from the end of a string?

For example, in the below code I want 'A-BC' from variable s and t, but my code only returns 'ABC'.

import string

s = 'A-BC/'
t = 'A-BC-'

s.translate(str.maketrans('', '', string.punctuation))
t.translate(str.maketrans('', '', string.punctuation))
1 Answers

You can use str.rstrip():

>>> import string
>>> s = 'A-BC/'

>>> s.rstrip(string.punctuation)
'A-BC'

Please refer str.rstrip() document for more details.

Related