杰瑞科技汇

Python 3.5.1的print函数如何使用?

Of course! Let's break down the print() function in Python 3.5.1.

This is a great question because Python 3.5.1 is a specific version, and understanding the print function is fundamental to Python.

The Basic Syntax

In Python 3, print is a function, not a statement like it was in Python 2. This means you must use parentheses .

The simplest form is:

print("Hello, World!")

Printing Multiple Items

You can print multiple items by separating them with a comma. By default, they will be printed with a space in between.

name = "Alice"
age = 30
print("Name:", name, "Age:", age)

Output:

Name: Alice Age: 30

The sep (Separator) Argument

The sep argument lets you specify what to put between the items you are printing. The default is a single space ().

# Default behavior (sep=' ')
print("apple", "banana", "cherry")
# Using a custom separator
print("apple", "banana", "cherry", sep=", ")
# Using no separator
print("apple", "banana", "cherry", sep="")

Output:

apple banana cherry
apple, banana, cherry
applebananacherry

The end Argument

The end argument specifies what to print at the end of the print() statement. The default is a newline character (\n), which moves the cursor to the next line.

This is very useful for creating progress bars or keeping the cursor on the same line.

# Default behavior (end='\n')
print("This is the first line.")
print("This is the second line.")
# Customizing the end character
print("Processing...", end=" ")
print("Done!")
# Using end to create a loading animation
import time
for i in range(5):
    print(f"Loading... {i+1}/5", end="\r")
    time.sleep(1)

Output:

This is the first line.
This is the second line.
Processing... Done!

(The loading animation will overwrite the line 5 times before finishing)

Printing to a File (The file Argument)

The file argument specifies where to send the output. By default, it prints to the standard output (your screen/console). You can change this to write to a file.

Important: When printing to a file, it's best practice to use a with statement to ensure the file is automatically closed, even if errors occur.

# Using a 'with' block (recommended)
with open("my_log.txt", "w") as f:
    print("This message will be saved to a file.", file=f)
    print("This is the second log entry.", file=f)
print("Log has been written to my_log.txt")

After running this, a file named my_log.txt will be created with the following content:

This message will be saved to a file.
This is the second log entry.

Common Mistake: Python 2 vs. Python 3

If you are used to Python 2, you might forget the parentheses.

  • Python 2 (Statement):

    print "Hello, World!"  # This works in Python 2
  • Python 3 (Function):

    print("Hello, World!")  # This is the correct syntax in Python 3

Summary Table for print() in Python 3.5.1

Argument Description Default Value Example
*objects The one or more objects you want to print. (Required) print("text", 123)
sep The separator string to place between objects. (a space) print("a", "b", sep="|")
end The string to append at the end of the output. '\n' (newline) print("No newline", end="")
file A file-like object (e.g., a file) to write to. sys.stdout (the console) print("to file", file=open("log.txt", "w"))

A Complete Example

Let's combine a few of these concepts.

# Data for a user profile
user_id = 9527
username = "charlie"
status = "active"
last_login = "2025-10-27 10:00:00"
# Print a formatted header
print("-" * 30)
print("      USER PROFILE      ")
print("-" * 30)
# Print the user details with custom separators and no newline at the end
print("User ID:", user_id, end=" | ")
print("Username:", username, end="\n")
# Print the status and last login on the same line
print("Status:", status, "| Last Login:", last_login)
# Write the same information to a log file
with open("user_log.txt", "a") as f: # 'a' for append mode
    print(f"User '{username}' (ID: {user_id}) logged in at {last_login}.", file=f)
print("\nProfile displayed and logged.")

Console Output:

----------------------------
      USER PROFILE      
----------------------------
User ID: 9527 | Username: charlie
Status: active | Last Login: 2025-10-27 10:00:00
Profile displayed and logged.

File user_log.txt content:

User 'charlie' (ID: 9527) logged in at 2025-10-27 10:00:00.
分享:
扫描分享到社交APP
上一篇
下一篇