如何将以\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
相关产品推荐
相关产品推荐

