Python here document without newlines at top and bottom
45,276
Solution 1
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
Add backslash \ at the end of unwanted lines:
text = '''\
cat
dog\
'''
It is somewhat more readable.
Solution 3
use parentheses:
print (
'''dog
cat'''
)
Use str.strip()
print '''
dog
cat
'''.strip()
use str.join()
print '\n'.join((
'dog',
'cat',
))
Solution 4
You could use strip()
:
print '''
dog
cat
'''.strip()
Solution 5
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='')
Author by
Juan
Updated on November 16, 2020Comments
-
Juan over 3 years
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.
-
0xC0000022L about 12 yearsMileage varies. He's asking heredoc, so let's give him that :)
-
Silas Ray about 12 yearsParens 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.
-
Juan about 12 yearsI 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.
-
user2622016 over 10 yearsThe backslash at the end of line
dog
makes it go away. Since this is not a raw string,\[newline]
is reduced to nothing -
bukzor over 10 yearsIt ends up looking awfully funny when the variable assignment is indented deeper than the module level (eg a method of a class).
-
Huw Walters over 8 yearsThank 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().
-
kdubs about 8 yearspretty sure he wants to print out more than cat dog. I know that's why I'm here
-
Ingmar over 2 yearsYep, but this is not exactly a pure here document. Nice idea anyway, some might like it.
-
chkpnt over 2 yearsHas the behaviour changed with Python 3? At least for raw-strings it doesn't seem to work any longer.
-
Starfish about 2 yearsThey asked for help, not judgment.