将参数写入应用程序。

这是Streamlit命令的瑞士军刀:根据你输入的内容,它会执行不同的操作。与其他Streamlit命令不同,write()具有一些独特的属性:

  1. 您可以传入多个参数,所有这些参数都将被写入。
  2. 其行为取决于输入类型,如下所示。
  3. 它返回 None,因此它在应用程序中的“槽位”无法被重用。
函数签名[source]

st.write(*args, unsafe_allow_html=False, **kwargs)

参数

*args (any)

One or many objects to print to the App.

Arguments are handled as follows:

  • write(string) : Prints the formatted Markdown string, with
    support for LaTeX expression, emoji shortcodes, and colored text. See docs for st.markdown for more.
  • write(dataframe) : Displays any dataframe-like object in an interactive table.
  • write(dict) : Displays dict-like in an interactive viewer.
  • write(list) : Displays list-like in an interactive viewer.
  • write(error) : Prints an exception specially.
  • write(func) : Displays information about a function.
  • write(module) : Displays information about a module.
  • write(class) : Displays information about a class.
  • write(DeltaGenerator) : Displays information about a DeltaGenerator.
  • write(mpl_fig) : Displays a Matplotlib figure.
  • write(generator) : Streams the output of a generator.
  • write(openai.Stream) : Streams the output of an OpenAI stream.
  • write(altair) : Displays an Altair chart.
  • write(PIL.Image) : Displays an image.
  • write(keras) : Displays a Keras model.
  • write(graphviz) : Displays a Graphviz graph.
  • write(plotly_fig) : Displays a Plotly figure.
  • write(bokeh_fig) : Displays a Bokeh figure.
  • write(sympy_expr) : Prints SymPy expression using LaTeX.
  • write(htmlable) : Prints _repr_html_() for the object if available.
  • write(db_cursor) : Displays DB API 2.0 cursor results in a table.
  • write(obj) : Prints str(obj) if otherwise unknown.

unsafe_allow_html (bool)

是否在*args内渲染HTML。这仅适用于字符串或回退到_repr_html_()的对象。如果为False(默认值),则在body中找到的任何HTML标签将被转义,因此被视为原始文本。如果为True,则在body中的任何HTML表达式将被渲染。

向您的应用程序添加自定义HTML会影响安全性、样式和可维护性。

注意

如果您只想插入HTML或CSS而不使用Markdown文本,我们建议使用st.html代替。

**kwargs (任何)

删除

**kwargs 已被弃用,并将在以后的版本中移除。 使用其他更具体的 Streamlit 命令来传递额外的 关键字参数。

关键字参数。未使用。

示例

它的基本用例是绘制Markdown格式的文本,当输入是字符串时:

import streamlit as st

st.write("Hello, *World!* :sunglasses:")

如前所述,st.write() 也接受其他数据格式,例如数字、数据框、样式化数据框和各种对象:

import streamlit as st
import pandas as pd

st.write(1234)
st.write(
    pd.DataFrame(
        {
            "first column": [1, 2, 3, 4],
            "second column": [10, 20, 30, 40],
        }
    )
)

最后,您可以传入多个参数来执行如下操作:

import streamlit as st

st.write("1 + 1 = ", 2)
st.write("Below is a DataFrame:", data_frame, "Above is a dataframe.")

哦,还有一件事:st.write 也接受图表对象!例如:

import streamlit as st
import pandas as pd
import numpy as np
import altair as alt

df = pd.DataFrame(np.random.randn(200, 3), columns=["a", "b", "c"])
c = (
    alt.Chart(df)
    .mark_circle()
    .encode(x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"])
)

st.write(c)

了解st.writemagic命令是什么以及如何使用它们。

forum

还有问题吗?

我们的 论坛 充满了有用的信息和Streamlit专家。