如何使用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
相关产品推荐
相关产品推荐

