如何在Bokeh Div的HTML标题中插入循环变量的实际值
问题原因
你直接将Names[i]写在HTML字符串内部时,Python只会将其识别为普通文本内容,不会主动解析为对应变量的取值,因此输出时只会显示字面量内容。
解决方法
推荐使用Python的字符串插值方案动态插入变量值,以下是两种常用实现方式:
方法1:f-string 插值(Python 3.6+ 推荐)
在三重引号前添加f标识,需要插入变量的位置用{变量名}包裹即可,注意CSS中原本的大括号需要双写{{}}做转义,避免被识别为插值符号。
示例代码如下:
from bokeh.models import Div from bokeh.io import show Names = ["filename1", "filename2", "filename3"] for name in Names: text = f""" <html> <head> <style> h1 {{text-align: center;}} p {{text-align: center;}} div {{text-align: center;}} </style> </head> <body> <h1>{name}</h1> <p>This is a paragraph.</p> <div>This is a div.</div> </body> </html> """ show(Div(text=text))
方法2:str.format() 兼容旧版本Python
如果使用的是Python 3.6以下版本,可以用str.format()方法实现插值,同样需要转义CSS的大括号:
from bokeh.models import Div from bokeh.io import show Names = ["filename1", "filename2", "filename3"] for name in Names: text = """ <html> <head> <style> h1 {{text-align: center;}} p {{text-align: center;}} div {{text-align: center;}} </style> </head> <body> <h1>{}</h1> <p>This is a paragraph.</p> <div>This is a div.</div> </body> </html> """.format(name) show(Div(text=text))
内容的提问来源于stack exchange,提问作者bogate
相关产品推荐
相关产品推荐

