Python here document without newlines at top and bottom

PythonStringPrintingHeredoc

Python Problem Overview


What's the best way to have a here document, without newlines at the top and bottom? For example:

print '''
dog
cat
'''

will have newlines at the top and bottom, and to get rid of them I have to do this:

print '''dog
cat'''

which I find to be much less readable.

Python Solutions


Solution 1 - Python

How about this?

print '''
dog
cat
'''[1:-1]

Or so long as there's no indentation on the first line or trailing space on the last:

print '''
dog
cat
'''.strip()

Or even, if you don't mind a bit more clutter before and after your string in exchange for being able to nicely indent it:

from textwrap import dedent

...

print dedent('''
    dog
    cat
    rabbit
    fox
''').strip()

Solution 2 - Python

Add backslash \ at the end of unwanted lines:

 text = '''\
 cat
 dog\
 '''

It is somewhat more readable.

Solution 3 - Python

use parentheses:

print (
'''dog
cat'''
)

Use str.strip()

print '''
dog
cat
'''.strip()

use str.join()

print '\n'.join((
    'dog',
    'cat',
    ))

Solution 4 - Python

You could use strip():

print '''
dog
cat
'''.strip()

Solution 5 - Python

Use a backslash at the start of the first line to avoid the first newline, and use the "end" modifier at the end to avoid the last:

    print ('''\
    dog
    cat
    ''', end='')

Solution 6 - Python

Do you actually need the multi-line syntax? Why not just emded a newline?

I find print "dog\ncat" far more readable than either.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJuanView Question on Stackoverflow
Solution 1 - PythonWeebleView Answer on Stackoverflow
Solution 2 - Pythonuser2622016View Answer on Stackoverflow
Solution 3 - PythonSingleNegationEliminationView Answer on Stackoverflow
Solution 4 - PythonNPEView Answer on Stackoverflow
Solution 5 - PythonNorthernDeanView Answer on Stackoverflow
Solution 6 - PythonTyler EavesView Answer on Stackoverflow