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

如何将字符串'[1,fish#, 15,bird#, 4,horse#]'格式化为'1,fish#15,bird#4,horse#'

字符串格式转换解决方案

核心思路

完成转换只需两步:

  • 移除字符串首尾的方括号 [ 和 ]
  • 将所有 , (逗号加空格)替换为纯逗号 ,

Python 实现

original_str = '[1,fish#, 15,bird#, 4,horse#]'
processed_str = original_str[1:-1].replace(', ', ',')
print(processed_str)  # 输出:1,fish#15,bird#4,horse#
  • original_str[1:-1] 通过切片直接去掉首尾的方括号
  • .replace(', ', ',') 批量替换所有带空格的分隔符

JavaScript 实现

const originalStr = '[1,fish#, 15,bird#, 4,horse#]';
const processedStr = originalStr.replace(/^\[|\]$/g, '').replace(/, /g, ',');
console.log(processedStr); // 输出:1,fish#15,bird#4,horse#
  • /^\[|\]$/g 正则匹配首尾的方括号并清空
  • /, /g 全局匹配所有 , 并替换为 ,

Java 实现

String originalStr = "[1,fish#, 15,bird#, 4,horse#]";
String processedStr = originalStr.substring(1, originalStr.length() - 1).replaceAll(", ", ",");
System.out.println(processedStr); // 输出:1,fish#15,bird#4,horse#
  • substring(1, originalStr.length() - 1) 截取掉首尾的方括号
  • replaceAll(", ", ",") 替换所有带空格的分隔符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:40:47