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

如何使用Python为逗号分隔的字符串各字段添加双引号包裹

Python实现方法

直接用字符串拆分、遍历加引号再拼接的逻辑即可实现,示例代码如下:

# 定义原始逗号分隔字符串
raw_industry_str = "Agriculture,Aquaculture,Forestry and Logging,Fishing Hunting and Trapping"
# 拆分后给每个元素加双引号,再用逗号拼接
target_str = ','.join(f'"{industry}"' for industry in raw_industry_str.split(','))
# 打印验证结果
print(target_str)

运行上述代码后输出结果完全符合需求:
"Agriculture","Aquaculture","Forestry and Logging","Fishing Hunting and Trapping"


可选兼容处理

如果你的原始行业字符串中可能存在元素本身包含双引号的场景,可以增加转义处理避免格式错误:

target_str = ','.join(f'"{industry.replace("\"", "\\\"")}"' for industry in raw_industry_str.split(','))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:42:02