杰瑞科技汇

Python displaytext如何实现文本显示?

Of course! The term "display text" in Python can mean a few different things, from the most basic command to more advanced formatting and user interaction.

Python displaytext如何实现文本显示?-图1
(图片来源网络,侵删)

Let's break it down, starting from the simplest and most common method.

The Basics: print()

The most fundamental way to display text in Python is with the print() function. It outputs text to the console (your terminal or command prompt).

Simple Text

To display a simple string of text, just put it inside quotes inside the print() function.

print("Hello, World!")

Output:

Python displaytext如何实现文本显示?-图2
(图片来源网络,侵删)
Hello, World!

You can use single () or double () quotes. It's best to be consistent within a project.

Displaying Variables

You can also display the value of a variable.

name = "Alice"
age = 30
print(name)
print(age)

Output:

Alice
30

Combining Text and Variables (The Easy Way)

You can use the operator to join strings and variables. Important: You can only add strings to strings. If you have a number (like age), you must first convert it to a string using str().

Python displaytext如何实现文本显示?-图3
(图片来源网络,侵删)
name = "Bob"
age = 42
# This works because both are strings
print("My name is " + name)
# This would cause an error without str(age)
# print("I am " + age + " years old.") # TypeError!
# The correct way:
print("I am " + str(age) + " years old.")

Output:

My name is Bob
I am 42 years old.

Better Ways to Combine Text: f-strings (Formatted String Literals)

Manually converting variables to strings and using can be tedious and error-prone. Since Python 3.6, the best and most popular way to format strings is with f-strings.

You simply put an f before the opening quote and place your variables inside curly braces .

name = "Charlie"
age = 25
city = "New York"
# Using an f-string
print(f"My name is {name}.")
print(f"I am {age} years old and I live in {city}.")

Output:

My name is Charlie.
I am 25 years old and I live in New York.

F-strings are clean, readable, and powerful. You can even perform calculations or call functions inside them.

a = 10
b = 5
print(f"The sum of {a} and {b} is {a + b}.")

Output:

The sum of 10 and 5 is 15.

Advanced Text Display in a GUI

If "display text" means showing text in a graphical user interface (GUI), you'll need a library like Tkinter (which comes built-in with Python) or PyQt.

Example with Tkinter (Simple Window)

This code creates a window with a label that displays text.

import tkinter as tk
# 1. Create the main window
window = tk.Tk()
window.title("My First GUI")
window.geometry("300x100") # Width x Height
# 2. Create a label widget to display text
#    - text: The text to display
#    - font: The font family and size
#    - fg: Foreground (text) color
label = tk.Label(
    window,
    text="Hello from a GUI!",
    font=("Arial", 14),
    fg="blue"
)
# 3. Pack the label into the window so it becomes visible
label.pack(pady=20) # pady adds some vertical padding
# 4. Start the Tkinter event loop (this keeps the window open)
window.mainloop()

When you run this, a small window will appear with the text "Hello from a GUI!".


Displaying Formatted Text in the Console

Sometimes you want to align text in columns or create neat tables in the console. The built-in string module has a format() method that is powerful for this.

Example: Creating a Table

# Using the older .format() method for alignment
# {:<10} means: left-align, in a space of 10 characters
# {:>10} means: right-align, in a space of 10 characters
# {:^10} means: center-align, in a space of 10 characters
# {:.2f} means: format as a floating-point number with 2 decimal places
header = "{:<10} {:<10} {:<10}".format("Item", "Quantity", "Price")
row1 = "{:<10} {:<10} ${:<9.2f}".format("Apple", 5, 1.25)
row2 = "{:<10} {:<10} ${:<9.2f}".format("Bread", 2, 3.50)
row3 = "{:<10} {:<10} ${:<9.2f}".format("Milk", 1, 2.99)
print(header)
print("-" * 30) # A separator line
print(row1)
print(row2)
print(row3)

Output:

Item       Quantity   Price     
------------------------------
Apple      5          $1.25    
Bread      2          $3.50    
Milk       1          $2.99    

While f-strings are often preferred for simple cases, str.format() is still very useful for complex console formatting.


Summary: Which one should you use?

Method When to Use Example
print() The default, for any basic console output. print("Hello")
f-strings The modern standard. For embedding variables and expressions into strings easily and readably. print(f"Value is {x}")
str.format() For advanced console formatting, like aligning columns in tables. print("{:<10}".format("text"))
GUI Libraries When you need to create windows, buttons, and other graphical elements. tk.Label(window, text="...")

For 95% of your text-displaying needs, print() with f-strings is the way to go.

分享:
扫描分享到社交APP
上一篇
下一篇