IPython Notebook: how to display() multiple objects without newline
Question:
Currently when I use display()
function in the IPython notebook I get newlines inserted between objects:
>>> display('first line', 'second line')
first line
second line
But I would like the print()
function’s behaviour where everything is kept on the same line, e.g.:
>>> print("all on", "one line")
all on one line
Is there a method of changing display
behaviour to do this?
Answers:
No, display
cannot prevent newlines, in part because there are no newlines to prevent. Each displayed object gets its own div
to sit in, and these are arranged vertically. You might be able to adjust this by futzing with CSS, but I wouldn’t recommend that.
The only way you could really get two objects to display side-by-side is to build your own object which encapsulates multiple displayed objects, and display that instead.
For instance, your simple string case:
class ListOfStrings(object):
def __init__(self, *strings):
self.strings = strings
def _repr_html_(self):
return ''.join( [
"<span class='listofstr'>%s</span>" % s
for s in self.strings
])
display(ListOfStrings("hi", "hello", "hello there"))
I had exactly reverse problem (n
not working) and I solved it from py side. You can use for example this
a = 'first line', 'second line' # This converts to tuple
display(" ".join(a))
With this result
'first line second line'
Currently when I use display()
function in the IPython notebook I get newlines inserted between objects:
>>> display('first line', 'second line')
first line
second line
But I would like the print()
function’s behaviour where everything is kept on the same line, e.g.:
>>> print("all on", "one line")
all on one line
Is there a method of changing display
behaviour to do this?
No, display
cannot prevent newlines, in part because there are no newlines to prevent. Each displayed object gets its own div
to sit in, and these are arranged vertically. You might be able to adjust this by futzing with CSS, but I wouldn’t recommend that.
The only way you could really get two objects to display side-by-side is to build your own object which encapsulates multiple displayed objects, and display that instead.
For instance, your simple string case:
class ListOfStrings(object):
def __init__(self, *strings):
self.strings = strings
def _repr_html_(self):
return ''.join( [
"<span class='listofstr'>%s</span>" % s
for s in self.strings
])
display(ListOfStrings("hi", "hello", "hello there"))
I had exactly reverse problem (n
not working) and I solved it from py side. You can use for example this
a = 'first line', 'second line' # This converts to tuple
display(" ".join(a))
With this result
'first line second line'