Python:还有什么 compact/efficient 方法可以从列表中删除后缀字符串?

Python: what's a more compact/efficient way to strip string of a suffix from list?

是否有一种更紧凑、更有效的方法来从给定列表中去除任何后缀的字符串,即:

sfxs = ['suffix1', 'sfx2', 'suffix333']
s = 'string-to-process-sfx2'
for sfx in sfxs:
    i = s.find(sfx)
    if not i == -1:
        s = s[:i]
        break

后缀长度不同

您可以使用re.sub

>>> import re
>>> sfxs = ['suffix1', 'sfx2', 'suffix333']
>>> s = 'string-to-process-sfx2'
>>> re.sub(r'(' + '|'.join(sfxs) + r')$', '',s)
'string-to-process-'
>>> re.sub(r'\b(' + '|'.join(sfxs) + r')$', '',s)
'string-to-process-'

>>> re.sub(r'-(' + '|'.join(sfxs) + r')$', '',s)
'string-to-process'

'|'.join(sfxs) 有助于以 | 作为分隔符加入 suffix 列表。所以 r'(' + '|'.join(sfxs) + r')$' 会形成一个像 (suff1|suff2|suff3|..)$ 这样的正则表达式。注意 $ 锚点,匹配行尾。所以这只会在最后匹配。

>>> re.sub(r'(' + '|'.join(sorted(sfxs, key=lambda x:len(x), reverse=True)) + r')$', '',s)
'string-to-process-'
sfxs = ['suffix1', 'sfx2', 'suffix333']
s = 'string-to-process-sfx2'
for sfx in sfxs:
    if sfx in s:
        s.replace(sfx, "")

应该做的。检查以确保后缀在字符串中,如果是则将其删除。

sfxs = ['suffix1', 'sfx2', 'suffix333']
s = 'string-to-process-sfx2'
for sfx in sfxs:
    if s.endswith(sfx):
        s = s[:-len(sfx)]
        break
print(s)

效率稍微高一些,因为字符串比较仅查看字符串的末尾。