58

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Juan
  • 3,667
  • 3
  • 28
  • 32

6 Answers6

79

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()
Weeble
  • 17,058
  • 3
  • 60
  • 75
  • I think your first approach is the most elegant, since you only affect the first and last whitespace character. I was using strip before through a function call. – Juan Mar 06 '12 at 18:25
39

Add backslash \ at the end of unwanted lines:

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

It is somewhat more readable.

user2622016
  • 6,060
  • 3
  • 32
  • 53
  • The backslash at the end of line `dog` makes it go away. Since this is not a raw string, `\[newline]` is reduced to nothing – user2622016 Jan 16 '14 at 08:46
  • It ends up looking awfully funny when the variable assignment is indented deeper than the module level (eg a method of a class). – bukzor Jan 16 '14 at 19:50
  • 1
    Thank you, exactly what I was looking for. I use here docs in Ruby and Bash (which do not add a newline before the first line), and it seems inelegant to remove it with a [1:] or strip(). – Huw Walters Aug 28 '15 at 15:56
  • Yep, but this is not exactly a _pure_ here document. Nice idea anyway, some might like it. – Ingmar Oct 21 '21 at 08:51
  • Has the behaviour changed with Python 3? At least for raw-strings it doesn't seem to work any longer. – chkpnt Nov 09 '21 at 20:44
22

use parentheses:

print (
'''dog
cat'''
)

Use str.strip()

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

use str.join()

print '\n'.join((
    'dog',
    'cat',
    ))
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • 1
    Parens I think is the way to go. It's readable, it's more concise than the strip method, more readable than the \n for long blocks, and it seems to conform to the official coding standards. – Silas Ray Mar 06 '12 at 18:13
6

You could use strip():

print '''
dog
cat
'''.strip()
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

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

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

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

Tyler Eaves
  • 12,879
  • 1
  • 32
  • 39