Python实现:检测特殊字符并提取字符串最后分隔符后的内容
Python提取特殊分隔符后的末尾内容
需求说明
给定包含多种动态特殊分隔符(如_、$、#)的字符串,提取最后一个特殊分隔符之后的内容,例如:
new_123_12313131→12313131new$123$12313131→12313131new#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)}'")
代码解释
- 分隔符集合:
separators可以根据实际业务需求添加更多特殊字符(如@、%等) - 定位分隔符:通过遍历字符串,记录最后一个出现的特殊分隔符的索引
- 内容提取:利用Python字符串切片,从最后一个分隔符的下一位开始截取;如果字符串中没有特殊分隔符,直接返回原字符串
内容的提问来源于stack exchange,提问作者newbiee
相关产品推荐
相关产品推荐

