【问题标题】:IPython display a string without the quote markIPython 显示不带引号的字符串
【发布时间】:2020-04-07 20:11:19
【问题描述】:

有没有办法使用IPyhton显示打印字符串而不打印引号?

from IPython.display import display

label = display('Hello world!', display_id = True)

输出是:

'Hello world!'

它包括引号。我不想把它打印成这样的 HTML:

display(HTML('Hello wolrd!'), display_id = True)

【问题讨论】:

    标签: python jupyter-notebook ipython


    【解决方案1】:

    试试 print():

    print('Hello world!')
    

    结果:

    Hello world!
    

    【讨论】:

    • print() 没有机会更新特定的打印行,而 display() 可以。想象一下,有多个打印件,每个打印件打印到单独的行,并且只想更新其中一个。使用 display() 您可以使用其 ID 引用某个标签。
    【解决方案2】:

    你可以试试这个:

    display(HTML('<pre>Hello wolrd!</pre>'), display_id = True)
    

    【讨论】:

      【解决方案3】:

      你可以重写String formmater(类似于display docstring with an int的例子):

      from IPython.display import display
      
      def str_formatter(string, pp, cycle):
          pp.text(string)
      
      plain = get_ipython().display_formatter.formatters['text/plain']
      plain.for_type(str, str_formatter)
      
      display("Hello World!")
      

      【讨论】:

        【解决方案4】:

        display 非常智能,它可以显示多种格式,但默认情况下它使用您传递的对象的 __repr__(但您也可以定义例如 _repr_html_、_repr_json_ 等,查看此以获取更多信息:https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html)。

        你可以这样解决你的问题:

        class printer(str):
            def __repr__(self):
               return self
            
        handle = display(printer('Hello world!'), display_id=True)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-11
          • 1970-01-01
          • 1970-01-01
          • 2016-07-30
          • 1970-01-01
          • 2018-07-19
          • 1970-01-01
          • 2011-04-16
          相关资源
          最近更新 更多