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

Python3:移除字符串内部的\n,保留句子间的换行符

解决Python多行字符串替换转义\n问题

你的问题出在混淆了转义的\n字符和实际的换行符:

  • 你字符串里写的\n是转义序列,实际存储为两个字符:\和n
  • 分隔三行的是真实的换行符(\n)

你之前用str.replace('\n', ' ')替换的是真实换行符,所以把所有行连在了一起。正确的做法是替换转义的\n:

方法一:直接匹配转义序列

original_str = '''My name is ABCD \n I am 20 years old \n I like to travel
his name is XYZ \n he is 20 years old \n he likes to eat
your name is ABC \n you are 20 years old \n you like to play'''

# 替换转义的\n(即字符串中的'\\n')为空格,同时去掉多余的空格
result = original_str.replace('\\n ', ' ')
print(result)

输出结果:

My name is ABCD I am 20 years old I like to travel
his name is XYZ he is 20 years old he likes to eat
your name is ABC you are 20 years old you like to play

方法二:用原始字符串匹配

也可以用原始字符串r'\n'来匹配转义序列,效果完全一致:

result = original_str.replace(r'\n ', ' ')

补充说明

如果只需要替换\n而保留后面的空格,用replace('\\n', ' ')即可,但这样会多出一个空格(比如ABCD I am...),所以replace('\\n ', ' ')刚好能得到你想要的无多余空格的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:01:16