如果单词的结尾类似于给定列表中的任何可能结尾,我想删除单词的结尾。我使用了以下代码:ending = ('os','o','as','a')def rchop(thestring): if thestring.endswith((ending)): return thestring[:-len((ending))] return thestringrchop('potatos')结果是:“锅”。但我想要这个:'potat'我怎样才能解决这个问题?
3 回答

摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
您当时正在按照结尾元组的长度(4 个元素)对字符串进行切片。这就是您收到错误字符串的原因。
endings = ('os','o','as','a')
def rchop(thestring):
for ending in endings:
if thestring.endswith(ending):
return thestring[:-len(ending)]
return thestring
print(rchop('potatos'))
返回:
potat

波斯汪
TA贡献1811条经验 获得超4个赞
或者试试这个(很短),(注意,即使在非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
正如预期的那样!!!
添加回答
举报
0/150
提交
取消