在python中将字符串的多行变成一长行

问题描述

| 说我有字符串:
string = \'\'\'
this line number 1
line 2
line 3
line 4
\'\'\'
您如何将其变成:
this is line number 1line 2line 3line4
有人知道吗?     

解决方法

        使用
join
splitlines
>>> string = \'\'\'
... this line number 1
... line 2
... line 3
... line 4
... \'\'\'
>>> \'\'.join(string.splitlines())
\'this line number 1line 2line 3line 4\'
这优于
.replace(\"\\n\",\"\")
,因为它处理
\\r\\n
\\n
>>> \"\".join(\"a\\r\\nb\\nc\".splitlines())
\'abc\'
>>> \"a\\r\\nb\\nc\".replace(\"\\n\",\"\")
\'a\\rbc\'
    ,        就像是:
string.replace(\"\\n\",\"\")
更新: 认为字符串将包含“ 6”是错误的。无论平台如何,用三引号引起来的字符串都将不包含“ 11”。但是正如@ bradley.ayers所说,使用
splitlines()
可能更安全,更实用。 下面是Notepad ++中显示的带有CRLF的代码: 上面的代码在Windows上有效。     ,        Python字符串替换
 print mystr.replace(\'\\n\',\'\');
    ,        
s = \'\'\'
this line number 1
line 2
line 3
line 4
\'\'\'.replace(\'\\n\',\'\')

print s
结果是:
this line number 1line 2line 3line 4
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...