IPython Notebook:如何在没有换行的情况下显示()多个对象

mrm*_*oey 13 python ipython ipython-notebook

目前,当我display()在IPython笔记本中使用函数时,我在对象之间插入了换行符:

>>> display('first line', 'second line') 
first line
second line
Run Code Online (Sandbox Code Playgroud)

但我希望print()所有内容保持在同一行的行为,例如:

>>> print("all on", "one line")
all onone line 
Run Code Online (Sandbox Code Playgroud)

是否有改变display行为的方法来做到这一点?

min*_*nrk 7

不,display不能阻止换行,部分原因是没有新行可以阻止.每个显示的对象都有自己div的坐位,这些是垂直排列的.您可以通过使用CSS进行调整来调整此值,但我不建议这样做.

你可以真正让两个对象并排显示的唯一方法是构建自己的对象,它封装了多个显示的对象,并显示它.

例如,你的简单字符串案例:

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"))
Run Code Online (Sandbox Code Playgroud)

示例笔记本