Skip to main content

Streamline Text Display with st.text() Function

Streamline Text Display with st.text() Function

The st.text() function is a simple and effective way to display plain text in a Streamlit application. Unlike st.write(), which can handle multiple types of content, st.text() is specifically designed for displaying text in a straightforward manner.


1. Displaying Simple Text

To display plain text, you can pass a string directly to st.text(). The text will be rendered in a monospaced font, making it suitable for code snippets or fixed text.

import streamlit as st

st.text("This is a simple text example displayed using st.text()!")

Here is an example demonstrating how to display simple text:

st.text("Welcome to our application!")
st.text("Streamlit is easy to use for creating data apps.")

2. Displaying Multi-line Text

The st.text() function can also handle multi-line text. You can achieve this by including newline characters in your string.

st.text("Line 1\nLine 2\nLine 3")

This will display the text as:

  • Line 1
  • Line 2
  • Line 3

3. Use Cases for st.text()

The st.text() function is ideal for displaying plain text, status messages, or simple notifications. It is useful when you want to present text without additional formatting or complexity.

import streamlit as st

status_message = "Data loading complete!"
st.text(status_message)

Output

In this example, the status message will be displayed clearly and simply.


4. Difference Between st.text() and st.write()

While both functions can display text, there are key differences:

  • st.text() is limited to plain text and is best for simple outputs.
  • st.write() can handle various data types and format them automatically.

Choose st.text() when you need a straightforward text output without additional formatting.

Example

import streamlit as st

# Status message
status_message = "Data loading complete!"

# Heading for the section
st.markdown("### Comparing `st.write` vs `st.text`")

# Using st.write (formatted output)
st.markdown("#### Output using `st.write` (Formatted):")
st.write(
    f"<div style='background-color: #123540; padding: 10px; border-radius: 5px;'>"
    f"<strong>{status_message}</strong></div>", unsafe_allow_html=True
)

# Adding some space between the two outputs
st.markdown("---")

# Using st.text (plain text)
st.markdown("#### Output using `st.text` (Plain Text):")
st.text(status_message)

Output

streamlit-text-vs-write-function-output

Conclusion

The st.text() function is a straightforward and efficient way to display plain text in Streamlit applications. While it lacks the flexibility of st.write(), it excels at presenting simple, unformatted text clearly and effectively.

Comments