【问题标题】:Remove punctuations from the end of a string (and not from the middle)从字符串末尾(而不是中间)删除标点符号
【发布时间】:2020-12-28 21:40:23
【问题描述】:

我怎样才能去掉字符串末尾的标点符号?

例如,在下面的代码中,我想要来自变量st'A-BC',但我的代码只返回'ABC'

import string

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

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

【问题讨论】:

    标签: python string replace translation


    【解决方案1】:

    你可以使用str.rstrip():

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

    详情请咨询str.rstrip() document

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 2011-03-07
      相关资源
      最近更新 更多