찾다
백엔드 개발파이썬 튜토리얼부품 쓰기 및 텍스트 요소 간소화

Streamlit Part Write and Text Elements

Getting Started with Streamlit: A Beginner's Guide

Code can be found here: GitHub - jamesbmour/blog_tutorials:

Video version of blog can be found here: https://youtu.be/EQcqNW7Nw7M

Introduction

Streamlit is an open-source app framework that allows you to create beautiful, interactive web applications with minimal effort. If you’re a data scientist, machine learning engineer, or anyone working with data, Streamlit is the perfect tool to turn your Python scripts into interactive apps quickly. In this tutorial, we will dive into the basics of Streamlit by exploring some of its powerful features, such as st.write(), magic commands, and text elements.

Let’s get started by building a simple app to demonstrate these functionalities!

Setting Up Your Streamlit Environment

Before we jump into the code, make sure you have Streamlit installed. If you haven't installed it yet, you can do so with the following command:

pip install streamlit

Now, let’s start coding our first Streamlit app.

Building Your First Streamlit App

1. Adding a Title to Your App

Streamlit makes it incredibly easy to add titles and headings to your app. The st.title() function allows you to display a large title at the top of your application, which serves as the main heading.

import streamlit as st

st.title("Introduction to Streamlit: Part 1")

This will display a large, bold title at the top of your app.

Streamlit Write Elements

Using st.write() for Versatile Output

The st.write() function is one of the most versatile functions in Streamlit. You can use it to display almost anything, including text, data frames, charts, and more—all with a single line of code.

Displaying a DataFrame

Let's start by displaying a simple DataFrame using st.write().

import pandas as pd

df = pd.DataFrame({
    "Column 1": [1, 2, 3, 4],
    "Column 2": [10, 20, 30, 40]
})

st.write("DataFrame using st.write() function")
st.write(df)

This code creates a DataFrame with two columns and displays it directly in your app. The beauty of st.write() is that it automatically formats the DataFrame into a neat table, complete with scroll bars if needed.

Displaying Markdown Text

Another cool feature of st.write() is its ability to render Markdown text. This allows you to add formatted text, such as headers, subheaders, and paragraphs, with ease.

markdown_txt = (
    "### This is a Markdown Header\\n"
    "#### This is a Markdown Subheader\\n"
    "This is a Markdown paragraph.\\n"
)
st.write(markdown_txt)

With just a few lines of code, you can add rich text to your app.

Streaming Data with st.write_stream()

Streamlit also allows you to stream data to your app in real-time using the st.write_stream() function. This is particularly useful for displaying data that updates over time, such as sensor readings or live analytics.

import time

st.write("## Streaming Data using st.write_stream() function")
stream_btn = st.button("Click Button to Stream Data")

TEXT = """
# Stream a generator, iterable, or stream-like sequence to the app.
"""

def stream_data(txt="Hello, World!"):
    for word in txt.split(" "):
        yield word + " "
        time.sleep(0.01)

if stream_btn:
    st.write_stream(stream_data(TEXT))

In this example, when the button is clicked, the app will start streaming data word by word from the TEXT string, simulating real-time data updates.

Streamlit Text Elements

In addition to data streaming, Streamlit provides several text elements to enhance the presentation of your app.

Headers and Subheaders

You can easily add headers and subheaders using st.header() and st.subheader():

st.header("This is a Header")
st.subheader("This is a Subheader")

These functions help structure your content, making your app more organized and visually appealing.

Captions

Captions are useful for adding small notes or explanations. You can add them using st.caption():

st.caption("This is a caption")

Displaying Code

If you want to display code snippets in your app, you can use st.code():

code_txt = """
import pandas as pd
import streamlit as st

st.title("Streamlit Tutorials")
for i in range(10):
    st.write(i)
"""
st.code(code_txt)

This will display the code in a nicely formatted, syntax-highlighted block.

Displaying Mathematical Expressions

For those who need to include mathematical equations, Streamlit supports LaTeX:

st.latex(r"e = mc^2")
st.latex(r"\\int_a^b x^2 dx")

These commands will render LaTeX equations directly in your app.

Adding Dividers

To separate different sections of your app, you can use st.divider():

st.write("This is some text below the divider.")
st.divider()
st.write("This is some other text below the divider.")

Dividers add a horizontal line between sections, helping to break up the content visually.

Conclusion

In this introductory tutorial, we covered the basics of Streamlit, including how to use st.write() to display data and text, and how to stream data using st.write_stream(). We also explored various text elements to enhance the structure and readability of your app.

Streamlit makes it incredibly easy to create interactive web applications with just a few lines of code. Whether you're building dashboards, data exploration tools, or any other data-driven app, Streamlit provides the tools you need to get started quickly.

In the next tutorial, we’ll dive deeper into widgets and interactivity features in Streamlit. Stay tuned!

このチュートリアルが役立つと思われた場合は、忘れずに共有し、他のコンテンツを購読してください。次の投稿でお会いしましょう!

私の執筆をサポートしたり、ビールをご馳走したい場合は: https://buymeacoffee.com/bmours

위 내용은 부품 쓰기 및 텍스트 요소 간소화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Python 학습 : 2 시간의 일일 연구가 충분합니까?Python 학습 : 2 시간의 일일 연구가 충분합니까?Apr 18, 2025 am 12:22 AM

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

웹 개발을위한 파이썬 : 주요 응용 프로그램웹 개발을위한 파이썬 : 주요 응용 프로그램Apr 18, 2025 am 12:20 AM

웹 개발에서 Python의 주요 응용 프로그램에는 Django 및 Flask 프레임 워크 사용, API 개발, 데이터 분석 및 시각화, 머신 러닝 및 AI 및 성능 최적화가 포함됩니다. 1. Django 및 Flask 프레임 워크 : Django는 복잡한 응용 분야의 빠른 개발에 적합하며 플라스크는 소형 또는 고도로 맞춤형 프로젝트에 적합합니다. 2. API 개발 : Flask 또는 DjangorestFramework를 사용하여 RESTFULAPI를 구축하십시오. 3. 데이터 분석 및 시각화 : Python을 사용하여 데이터를 처리하고 웹 인터페이스를 통해 표시합니다. 4. 머신 러닝 및 AI : 파이썬은 지능형 웹 애플리케이션을 구축하는 데 사용됩니다. 5. 성능 최적화 : 비동기 프로그래밍, 캐싱 및 코드를 통해 최적화

Python vs. C : 성능과 효율성 탐색Python vs. C : 성능과 효율성 탐색Apr 18, 2025 am 12:20 AM

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

Python in Action : 실제 예제Python in Action : 실제 예제Apr 18, 2025 am 12:18 AM

Python의 실제 응용 프로그램에는 데이터 분석, 웹 개발, 인공 지능 및 자동화가 포함됩니다. 1) 데이터 분석에서 Python은 Pandas 및 Matplotlib를 사용하여 데이터를 처리하고 시각화합니다. 2) 웹 개발에서 Django 및 Flask 프레임 워크는 웹 응용 프로그램 생성을 단순화합니다. 3) 인공 지능 분야에서 Tensorflow와 Pytorch는 모델을 구축하고 훈련시키는 데 사용됩니다. 4) 자동화 측면에서 파이썬 스크립트는 파일 복사와 같은 작업에 사용할 수 있습니다.

Python의 주요 용도 : 포괄적 인 개요Python의 주요 용도 : 포괄적 인 개요Apr 18, 2025 am 12:18 AM

Python은 데이터 과학, 웹 개발 및 자동화 스크립팅 필드에 널리 사용됩니다. 1) 데이터 과학에서 Python은 Numpy 및 Pandas와 같은 라이브러리를 통해 데이터 처리 및 분석을 단순화합니다. 2) 웹 개발에서 Django 및 Flask 프레임 워크를 통해 개발자는 응용 프로그램을 신속하게 구축 할 수 있습니다. 3) 자동 스크립트에서 Python의 단순성과 표준 라이브러리가 이상적입니다.

파이썬의 주요 목적 : 유연성과 사용 편의성파이썬의 주요 목적 : 유연성과 사용 편의성Apr 17, 2025 am 12:14 AM

Python의 유연성은 다중 파리가 지원 및 동적 유형 시스템에 반영되며, 사용 편의성은 간단한 구문 및 풍부한 표준 라이브러리에서 나옵니다. 유연성 : 객체 지향, 기능 및 절차 프로그래밍을 지원하며 동적 유형 시스템은 개발 효율성을 향상시킵니다. 2. 사용 편의성 : 문법은 자연 언어에 가깝고 표준 라이브러리는 광범위한 기능을 다루며 개발 프로세스를 단순화합니다.

파이썬 : 다목적 프로그래밍의 힘파이썬 : 다목적 프로그래밍의 힘Apr 17, 2025 am 12:09 AM

Python은 초보자부터 고급 개발자에 이르기까지 모든 요구에 적합한 단순성과 힘에 호의적입니다. 다목적 성은 다음과 같이 반영됩니다. 1) 배우고 사용하기 쉽고 간단한 구문; 2) Numpy, Pandas 등과 같은 풍부한 라이브러리 및 프레임 워크; 3) 다양한 운영 체제에서 실행할 수있는 크로스 플랫폼 지원; 4) 작업 효율성을 향상시키기위한 스크립팅 및 자동화 작업에 적합합니다.

하루 2 시간 안에 파이썬 학습 : 실용 가이드하루 2 시간 안에 파이썬 학습 : 실용 가이드Apr 17, 2025 am 12:05 AM

예, 하루에 2 시간 후에 파이썬을 배우십시오. 1. 합리적인 학습 계획 개발, 2. 올바른 학습 자원을 선택하십시오. 3. 실습을 통해 학습 된 지식을 통합하십시오. 이 단계는 짧은 시간 안에 Python을 마스터하는 데 도움이 될 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는