【问题标题】:IPython Notebook: how to display() multiple objects without newlineIPython Notebook:如何在没有换行符的情况下显示()多个对象
【发布时间】:2013-07-03 03:29:20
【问题描述】:

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

>>> display('first line', 'second line') 
first line
second line

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

>>> print("all on", "one line")
all on one line 

有没有办法改变display 的行为来做到这一点?

【问题讨论】:

    标签: python jupyter-notebook ipython


    【解决方案1】:

    不,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"))
    

    example notebook

    【讨论】:

      猜你喜欢
      • 2013-12-10
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      相关资源
      最近更新 更多