从字符串末尾(而不是中间)删除标点符号
Remove punctuations from the end of a string (and not from the middle)
如何去掉字符串末尾的标点符号?
例如,在下面的代码中,我想要 'A-BC'
来自变量 s
和 t
,但我的代码只有 returns 'ABC'
.
import string
s = 'A-BC/'
t = 'A-BC-'
s.translate(str.maketrans('', '', string.punctuation))
t.translate(str.maketrans('', '', string.punctuation))
您可以使用 str.rstrip()
:
>>> import string
>>> s = 'A-BC/'
>>> s.rstrip(string.punctuation)
'A-BC'
详情请参考str.rstrip()
document。
如何去掉字符串末尾的标点符号?
例如,在下面的代码中,我想要 'A-BC'
来自变量 s
和 t
,但我的代码只有 returns 'ABC'
.
import string
s = 'A-BC/'
t = 'A-BC-'
s.translate(str.maketrans('', '', string.punctuation))
t.translate(str.maketrans('', '', string.punctuation))
您可以使用 str.rstrip()
:
>>> import string
>>> s = 'A-BC/'
>>> s.rstrip(string.punctuation)
'A-BC'
详情请参考str.rstrip()
document。