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

Python:如何移除元组内字符串列表最后一个“-”及之前的字符

解决方案

针对你给出的由字符串列表组成的元组,要移除每个字符串中最后一个“-”及其之前的内容,可以用Python的字符串内置方法快速实现,以下是两种简洁的方案:

方法一:使用rsplit()分割

rsplit()支持从字符串右侧开始指定次数分割,设置分割次数为1后,直接取分割结果的最后一段即可:

# 原始数据
my_tuple = (['https://wwww.example.com/watch/random-video-12'], ['https://wwww.example.com/watch/random-video-t-14'], ['https://www.example.com/watch/random-video-longest-1'])

# 处理并提取目标内容
result = []
for sub_list in my_tuple:
    target_part = sub_list[0].rsplit('-', 1)[-1]
    result.append(target_part)

print(result)  # 输出:['12', '14', '1']

方法二:使用rpartition()分割

rpartition()会将字符串从右侧第一个“-”处拆分为三个部分(前缀、分隔符、后缀),直接取第三部分就是需要的内容:

my_tuple = (['https://wwww.example.com/watch/random-video-12'], ['https://wwww.example.com/watch/random-video-t-14'], ['https://www.example.com/watch/random-video-longest-1'])

result = []
for sub_list in my_tuple:
    target_part = sub_list[0].rpartition('-')[2]
    result.append(target_part)

print(result)  # 输出:['12', '14', '1']

如果需要保留原元组嵌套列表的结构,可修改代码为:

my_tuple = (['https://wwww.example.com/watch/random-video-12'], ['https://wwww.example.com/watch/random-video-t-14'], ['https://www.example.com/watch/random-video-longest-1'])

result_tuple = tuple([sub_list[0].rsplit('-', 1)[-1]] for sub_list in my_tuple)
print(result_tuple)  # 输出:(['12'], ['14'], ['1'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 02:33:29