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

Python实现:检测特殊字符并提取字符串最后分隔符后的内容

Python提取特殊分隔符后的末尾内容

需求说明

给定包含多种动态特殊分隔符(如_、$、#)的字符串,提取最后一个特殊分隔符之后的内容,例如:

  • new_123_12313131 → 12313131
  • new$123$12313131 → 12313131
  • new#123#12313131 → 12313131

实现代码

def extract_last_part(s):
    # 自定义特殊分隔符集合,可根据需求扩展
    separators = {'_', '$', '#'}
    last_sep_index = -1
    
    # 遍历字符串,定位最后一个特殊分隔符的位置
    for idx, char in enumerate(s):
        if char in separators:
            last_sep_index = idx
    
    # 有分隔符则返回后续内容,无分隔符返回原字符串
    return s[last_sep_index + 1:] if last_sep_index != -1 else s

# 测试用例
test_cases = [
    "new_123_12313131",
    "new$123$12313131",
    "new#123#12313131",
    "no_separator_here",
    "mix$sep#test_12345"
]

for case in test_cases:
    print(f"原字符串: '{case}' → 提取结果: '{extract_last_part(case)}'")

代码解释

  1. 分隔符集合:separators可以根据实际业务需求添加更多特殊字符(如@、%等)
  2. 定位分隔符:通过遍历字符串,记录最后一个出现的特殊分隔符的索引
  3. 内容提取:利用Python字符串切片,从最后一个分隔符的下一位开始截取;如果字符串中没有特殊分隔符,直接返回原字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:45:13