You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用最简方式(优选单行代码)在Python中替换字符串后缀?

实现仅替换字符串末尾指定后缀的需求

要实现仅当字符串以特定后缀结尾时才替换该后缀,否则保持原字符串不变的需求,有两种简洁的单行实现方式:

方法1:使用字符串原生方法(Python 3.9+)

利用removesuffix()精准移除末尾后缀,结合endswith()判断是否需要添加新后缀:

# 针对你的场景,旧后缀为".wo",新后缀为".he"
string1 = "hello.world.wo"
string2 = "hello.world"

# 处理string1
print(string1.removesuffix(".wo") + ".he" if string1.endswith(".wo") else string1)
# 输出:'hello.world.he'

# 处理string2
print(string2.removesuffix(".wo") + ".he" if string2.endswith(".wo") else string2)
# 输出:'hello.world'

原理

  • endswith(".wo")先判断字符串是否以目标后缀结尾,避免给无后缀的字符串错误添加新后缀
  • removesuffix(".wo")只会移除末尾的匹配后缀,不会影响字符串中间的相同子串(比如不会把hello.world里的world误处理)

方法2:使用正则表达式(兼容全Python版本)

通过正则的$锚点匹配字符串末尾,实现精准替换:

import re

string1 = "hello.world.wo"
string2 = "hello.world"

# 处理string1
print(re.sub(r'\.wo$', '.he', string1))
# 输出:'hello.world.he'

# 处理string2
print(re.sub(r'\.wo$', '.he', string2))
# 输出:'hello.world'

原理

  • r'\.wo$'中的$表示匹配字符串的末尾位置,确保只替换末尾的.wo
  • 若字符串不存在该后缀,正则不会做任何替换,直接返回原字符串

两种方法都能满足需求,优先推荐方法1(无需额外模块,语义更直观);如果需要兼容Python 3.9之前的版本,选择方法2即可。

内容的提问来源于stack exchange,提问作者Programer Beginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:45:30