Python - 根据结尾列表删除单词的结尾

如果单词的结尾类似于给定列表中的任何可能结尾,我想删除单词的结尾。我使用了以下代码:


ending = ('os','o','as','a')


def rchop(thestring):

  if thestring.endswith((ending)):

    return thestring[:-len((ending))]

  return thestring


rchop('potatos')

结果是:“锅”。但我想要这个:'potat'


我怎样才能解决这个问题?


守候你守候我
浏览 202回答 3
3回答

摇曳的蔷薇

您当时正在按照结尾元组的长度(4 个元素)对字符串进行切片。这就是您收到错误字符串的原因。endings = ('os','o','as','a')def rchop(thestring):    for ending in endings:        if thestring.endswith(ending):            return thestring[:-len(ending)]    return thestringprint(rchop('potatos'))返回:potat

波斯汪

或者试试这个(很短),(注意,即使在非ending元素位于字符串末尾时也能工作):def f(s):    s2=next((i for i in ending if s.endswith(i)),'')    return s[:len(s)-len(s2)]现在:print(f('potatos'))是:potat正如预期的那样!!!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python