Reputation: 22449
I am trying to save to a txt a multi-line string without the newline and any multiple spaces:
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" )
When I open the file cat 'text.txt'
the file is on multiple lines. How can I have the code written in a single line without multiple white spaces?
<rect x="0" y="0" width="3" height="4" stroke="red" stroke-width="1" fill-opacity="0" />
Without using for instance "".join()
or other methods which will affect the readability of the code?
Using .replace('\n', '')
will not delete the multiple white space.
Upvotes: -1
Views: 1838
Reputation: 2780
Add .replace('\n', '')
at the end of the string.
Edited: And by "at the end of the string", I mean the multi-line one, e.g.:
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
Another possibility is to benefit from Python's automatic concatenation of strings, as follows:
f.write('<rect '
'x="0" '
'y="0" '
'width="%s" '
'height="%s" '
'stroke="red" '
'stroke-width="1" '
'fill-opacity="0"/> ' % (3,4) + '\n')
Upvotes: 1
Reputation: 3
I'm guessing that you want all the code in 1 line for the multi line string?
then just do it like this
f.write(r"""<rect x="0" y="0" width="%s"
ect...
That way you are putting everything on one line
Hope this helps
Upvotes: 0