gpt4 book ai didi

python - 仅在字符串末尾删除子字符串

转载 作者:IT老高 更新时间:2023-10-28 20:27:08 26 4
gpt4 key购买 nike

我有一堆字符串,其中一些有'rec'。仅当这些是最后 4 个字符时,我才想删除它。

也就是说我有

somestring = 'this is some string rec'

我希望它变成

somestring = 'this is some string'

解决这个问题的 Python 方法是什么?

最佳答案

def rchop(s, suffix):
if suffix and s.endswith(suffix):
return s[:-len(suffix)]
return s

somestring = 'this is some string rec'
rchop(somestring, ' rec') # returns 'this is some string'

关于python - 仅在字符串末尾删除子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3663450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com