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

如何将以\n分隔的Python多行字符串合并为单行字符串?

将多行字符串合并为单行的几种Python方法

以下是几种把以\n分隔的多行字符串合并成单行的可行方法:

  • 方法一:使用str.replace()
    这是你已经想到的方法,直接替换所有换行符为空字符串:
s = """Text line
another text line
and another long text line"""

s = s.replace('\n', '')
print(s)  # 输出: Text lineanother text lineand another long text line
  • 方法二:使用str.join()配合splitlines()
    先把字符串按行分割成列表,再用空字符串拼接所有元素:
s = """Text line
another text line
and another long text line"""

s = ''.join(s.splitlines())
print(s)

如果字符串包含\r\n这类Windows换行符,splitlines()能自动处理,兼容性更强。

  • 方法三:使用正则表达式re.sub()
    用正则匹配换行符并替换为空,还能兼容多种换行格式:
import re

s = """Text line
another text line
and another long text line"""

# 替换单个\n
s = re.sub(r'\n', '', s)
# 如需兼容\r\n,可改为 re.sub(r'[\r\n]', '', s)
print(s)
  • 方法四:使用str.translate()
    创建转换表映射换行符为空,实现快速替换:
s = """Text line
another text line
and another long text line"""

s = s.translate(str.maketrans('', '', '\n'))
print(s)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:35:25