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

Python中如何基于组合字符拆分拼接在一起的多路径字符串

现有代码问题说明

  1. split() 方法不会修改原字符串,你没有接收拆分后的返回值,操作完没有任何实际效果
  2. 直接按\p拆分后,得到的有效片段都会丢失开头的\p前缀,需要单独补回
  3. Python中反斜杠是转义字符,处理路径时建议在字符串前加r声明为原始字符串,避免转义逻辑干扰内容

实现代码

基础遍历写法

适配列表中存在多个拼接字符串的场景:

# 原始数据,加r声明为原始字符串避免转义问题
list_string = [r"\path\to\file1.json\path\to\file2.json\path\to\file3.json"]
res = []
for line in list_string:
    # 按\p拆分字符串
    parts = line.split(r'\p')
    for p in parts:
        # 过滤拆分出来的空值,给有效路径补回前缀
        if p.strip():
            res.append(r'\p' + p)
# 替换原列表
list_string = res

简洁列表推导式写法

如果你的列表始终只有1个拼接字符串元素,可以直接简化为:

list_string = [r"\path\to\file1.json\path\to\file2.json\path\to\file3.json"]
list_string = [r'\p' + p for p in list_string[0].split(r'\p') if p]

运行后得到的list_string就是你需要的结果:

["\\path\\to\\file1.json", "\\path\\to\\file2.json", "\\path\\to\\file3.json"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:30:03