简体   繁体   中英

How to save a multi-line string in a single line and without multiple white spaces

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.

Add .replace('\\n', '') at the end of the string.

Edited: And by "at the end of the string", I mean the multi-line one, eg:

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM