[英]How to save a multi-line string in a single line and without multiple white spaces
我试图将没有换行符和任何多个空格的多行字符串保存到txt:
with open('test.txt','w') as f:
f.write( r"""<rect
x="0"
y="0"
width="%s"
height="%s"
stroke="red"
stroke-width="1"
fill-opacity="0" />""" %(3,4)+"\n" )
当我打开文件cat 'text.txt'
,文件位于多行上。 如何将代码写在没有多个空格的一行中?
<rect x="0" y="0" width="3" height="4" stroke="red" stroke-width="1" fill-opacity="0" />
是否不使用例如"".join()
或其他会影响代码可读性的方法?
使用.replace('\\n', '')
不会删除多个空格。
在字符串末尾添加.replace('\\n', '')
。
编辑:“在字符串的末尾”是指多行,例如:
f.write( r"""<rect
x="0"
y="0"
width="%s"
height="%s"
stroke="red"
stroke-width="1"
fill-opacity="0" />""".replace('\n', '') %(3,4)+"\n" )
^^^^^^^^^^^^^^^^^^
HERE
另一种可能性是受益于Python的字符串自动连接,如下所示:
f.write('<rect '
'x="0" '
'y="0" '
'width="%s" '
'height="%s" '
'stroke="red" '
'stroke-width="1" '
'fill-opacity="0"/> ' % (3,4) + '\n')
我猜想您希望多行字符串的所有代码都在1行中吗?
然后就这样做
f.write(r"""<rect x="0" y="0" width="%s"
等等...
这样一来,您可以将所有内容都放在一条线上
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.