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

求助:如何在Python中移除列表字符串里;到::间的子串

移除字符串列表中";"到"::"之间内容的实现方法

你的问题出在原代码用切片直接截取了需要删除的区间,而不是保留前后两部分。要实现需求,你需要把分号及之前的内容,和"::"之后的内容拼接起来,或者用正则表达式批量替换。

方法一:字符串拼接(基础版)

直接通过字符串索引定位标记位置,拼接前后两段内容:

inp = ["_ZN8GameMode4tickEv ; Player::tick(void)", "demo ; Test::hello()"]
result = [
    i[:i.find(";") + 2] + i[i.find("::") + 2:]
    for i in inp
]
print(result)
# 输出: ['_ZN8GameMode4tickEv ; tick(void)', 'demo ; hello()']

说明:

  • i[:i.find(";") + 2]:截取从开头到"; "(分号+空格)的所有内容
  • i[i.find("::") + 2:]:截取从"::"结束位置到字符串末尾的内容
  • 两者拼接后就得到了去掉中间冗余部分的结果

方法二:带边界判断的字符串处理(健壮版)

如果你的列表中存在没有";"或"::"的字符串,可以添加判断逻辑避免报错:

def clean_target_string(s):
    semicolon_idx = s.find(";")
    double_colon_idx = s.find("::")
    # 确保两个标记都存在,且分号在::之前
    if semicolon_idx != -1 and double_colon_idx != -1 and semicolon_idx < double_colon_idx:
        return s[:semicolon_idx + 2] + s[double_colon_idx + 2:]
    # 不符合条件则返回原字符串
    return s

inp = [
    "_ZN8GameMode4tickEv ; Player::tick(void)",
    "missing semicolon::example",
    "missing double colon ; test"
]
result = [clean_target_string(s) for s in inp]
print(result)
# 输出: ['_ZN8GameMode4tickEv ; tick(void)', 'missing semicolon::example', 'missing double colon ; test']

方法三:正则表达式(灵活版)

如果分号和"::"之间的内容格式不固定(比如分号后有多个空格),用正则表达式更灵活:

import re

inp = [
    "_ZN8GameMode4tickEv ; Player::tick(void)",
    "demo;   MultiWord::func(int)",
    "test ;::edge_case"
]
# 匹配从";"到"::"的所有内容,非贪婪模式避免过度匹配
pattern = re.compile(r';.*?::')
# 替换为"; ",保留分号和必要空格
result = [pattern.sub(r'; ', s) for s in inp]
print(result)
# 输出: ['_ZN8GameMode4tickEv ; tick(void)', 'demo; func(int)', 'test ; edge_case']

正则说明:

  • ;.*?:::匹配以";"开头,直到第一个"::"结束的所有内容(.*?是非贪婪匹配,防止匹配到后续的"::")
  • pattern.sub(r'; ', s):把匹配到的内容替换成"; ",直接完成内容移除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:32:50