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

如何获取字符串中倒数第二个下划线(_)之前的部分?

解决方法

现有如下字符串:

'HOLA1_HOLA2_HOLA3_HOLA4'
'HOLA1_HOLA2_HOLA3_HOLA4_HOLA5'

需要获取到倒数第二个下划线出现位置为止的部分,预期结果:

'HOLA1_HOLA2'
'HOLA1_HOLA2_HOLA3'

这里提供两种简单的实现方式(以Python为例):

方法一:分割后重组

通过下划线分割字符串为列表,舍弃最后两个元素后重新拼接:

# 处理第一个字符串
s1 = 'HOLA1_HOLA2_HOLA3_HOLA4'
res1 = '_'.join(s1.split('_')[:-2])
print(res1)  # 输出 'HOLA1_HOLA2'

# 处理第二个字符串
s2 = 'HOLA1_HOLA2_HOLA3_HOLA4_HOLA5'
res2 = '_'.join(s2.split('_')[:-2])
print(res2)  # 输出 'HOLA1_HOLA2_HOLA3'

方法二:定位倒数第二个下划线索引

先找到最后一个下划线的位置,再在其之前定位倒数第二个下划线,最后截取对应区间:

# 处理第一个字符串
s1 = 'HOLA1_HOLA2_HOLA3_HOLA4'
last_idx = s1.rfind('_')
second_last_idx = s1.rfind('_', 0, last_idx)
res1 = s1[:second_last_idx]
print(res1)  # 输出 'HOLA1_HOLA2'

# 处理第二个字符串
s2 = 'HOLA1_HOLA2_HOLA3_HOLA4_HOLA5'
last_idx = s2.rfind('_')
second_last_idx = s2.rfind('_', 0, last_idx)
res2 = s2[:second_last_idx]
print(res2)  # 输出 'HOLA1_HOLA2_HOLA3'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:10:22