杰瑞科技汇

Python print如何实现缩进输出?

Of course! In Python, "indent" can mean two main things:

Python print如何实现缩进输出?-图1
(图片来源网络,侵删)
  1. Indenting the source code itself (using spaces or tabs) to define code blocks. This is a fundamental rule of the Python language.
  2. Adding indentation/spaces to the output of a print() statement to format text nicely.

Let's cover both.


Code Indentation (The Fundamental Rule)

In Python, indentation is not just for readability; it's syntactically significant. It defines which statements belong together in a block, such as the code inside a loop, a function, or an if statement.

You must use either spaces or tabs for indentation, but you cannot mix them in the same file. The standard convention is to use 4 spaces for each level of indentation.

How it Works

  • The line(s) immediately following a statement that ends with a colon are indented.
  • All indented lines at the same level belong to the same block.

Example

# The 'if' statement ends with a ':', so the next line is indented.
# This indented block only runs if the condition is True.
if 5 > 2:
    print("Five is greater than two!") # This is inside the 'if' block
    print("This line is also part of the 'if' block.") # Same indentation level
# This line is NOT indented, so it's outside the 'if' block.
# It will run regardless of the condition.
print("This will always print.")
# Another example with a function
def greet(name):
    # This entire block belongs to the 'greet' function
    print(f"Hello, {name}!")
    print("How are you today?")
# This line calls the function. It's not indented.
greet("Alice")
# This will cause an IndentationError
# if 5 > 2:
# print("This is wrong and will fail!")

Key Takeaway: Proper code indentation is mandatory for your Python program to run. An IndentationError will occur if it's incorrect.

Python print如何实现缩进输出?-图2
(图片来源网络,侵删)

Indenting Print Output (Formatting Text)

This is what most people mean when they ask about "print indent". You want to add spaces or tabs to the beginning of the line of text you are printing.

Here are the most common and effective ways to do this.

Method 1: Using an f-string (Recommended for Python 3.6+)

This is the most modern, readable, and flexible way to format strings.

name = "Bob"
age = 30
# Add 4 spaces of indentation
print(f"    Hello, my name is {name} and I am {age} years old.")
# Add a variable amount of indentation
indent_level = 8
print(f"{' ' * indent_level}This line is indented by 8 spaces.")

Output:

Python print如何实现缩进输出?-图3
(图片来源网络,侵删)
    Hello, my name is Bob and I am 30 years old.
        This line is indented by 8 spaces.

Method 2: Using the str.rjust() Method

This method right-justifies a string in a field of a given width. The extra space is filled with spaces by default.

text = "Right-aligned text"
# The first argument is the total width of the field.
# The string will be padded with spaces on the left to reach this width.
print(text.rjust(30))
# You can also specify a different fill character, like a dot (.)
print(text.rjust(30, '.'))

Output:

            Right-aligned text
..............Right-aligned text

Method 3: Using the str.ljust() Method

This is the opposite of rjust(). It left-justifies the string. While it doesn't indent the text itself, it's useful for creating columns where the next piece of text starts at a fixed point.

label1 = "Name:"
label2 = "Age:"
value1 = "Alice"
value2 = "30"
# Create two columns of width 10
print(f"{label1.ljust(10)}{value1}")
print(f"{label2.ljust(10)}{value2}")

Output:

Name:     Alice
Age:      30

Method 4: Using the print() function's sep and end parameters

This is a clever trick. By default, print() adds a space () between arguments and a newline ('\n') at the end. You can change this.

# We want to print 4 spaces, then the text.
# We use an empty string for 'sep' so nothing is added between the parts.
# We use an empty string for 'end' so a newline isn't added automatically.
print("    ", "This is indented using the sep parameter.", sep="")
# To print a multi-line indented block:
print("    Line 1 of the indented block.")
print("    Line 2 of the indented block.")
print("    Line 3 of the indented block.")

Output:

This is indented using the sep parameter.
    Line 1 of the indented block.
    Line 2 of the indented block.
    Line 3 of the indented block.

Summary: Which Method to Use?

Method Best For Example
f-string Most cases. Simple, readable, and flexible indentation. print(f" {my_variable}")
str.rjust() When you need a text block to be a specific total width. print(my_text.rjust(20))
str.ljust() Creating aligned columns of text. print("Label:".ljust(10) + "Value")
print() params Quick one-off indents or when you need precise control over separators. print(" ", "text", sep="")

For simply adding spaces to the start of a line, the f-string method is the clear winner for its simplicity and readability.

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