gpt4 book ai didi

python - 如何替换字符串的后缀?

转载 作者:行者123 更新时间:2023-11-28 19:45:49 34 4
gpt4 key购买 nike

我知道如何在 Python 中进行字符串替换,但我需要一种仅当序列位于单词末尾时才进行替换的方法。

例如:

rule: at -> ate
so:
cat -> cate
but:
attorney -> attorney

最佳答案

没有特殊的方法可以做到这一点,但无论如何它都很简单:

w = 'at'
repl = 'ate'
s = 'cat'

if s.endswith(w):
# if s ends with w, take only the part before w and add the replacement
s = s[:-len(w)] + repl

关于python - 如何替换字符串的后缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6363286/

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