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

如何在Python/Java中通过子串位置向字符串插入换行符?

在Python和Java中通过指定子串插入换行符的实现方法

完全可行,以下是两种语言的具体实现方式:

Python 实现

利用字符串内置的replace()方法,将目标子串'],替换为'],\n即可达到需求效果。

示例代码

# 直接使用字符串作为输入
input_str = "[[a,b,c], [d,e,f]]"
result = input_str.replace('],', '],\n')
print(result)

输出结果

[[a,b,c],
[d,e,f]]

如果你的输入是列表类型,需要先将其转换为字符串再处理:

input_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
input_str = str(input_list)
result = input_str.replace('],', '],\n')
print(result)

Java 实现

Java中同样可以使用String类的replace()方法完成替换操作。

示例代码

public class InsertNewLine {
    public static void main(String[] args) {
        String inputStr = "[[a,b,c], [d,e,f]]";
        String result = inputStr.replace("],", "],\n");
        System.out.println(result);
    }
}

输出结果

[[a,b,c],
[d,e,f]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:17:11