杰瑞科技汇

Python format()方法有哪些使用技巧?

Of course! "Python format and" is likely referring to string formatting and other related formatting operations in Python. This is a fundamental skill for any Python developer.

Let's break down the different ways to format strings in Python, from the oldest to the most modern and recommended methods.


The Short Answer: The Modern Way (f-strings)

For new code, you should almost always use f-strings (formatted string literals). They are fast, readable, and concise.

name = "Alice"
age = 30
product = "Python Guide"
# Use an 'f' before the string and curly braces {} for variables
message = f"Hello, {name}. You are {age} years old. Here is your {product}."
print(message)
# Output: Hello, Alice. You are 30 years old. Here is your Python Guide.

Detailed Breakdown of Formatting Methods

Here are the main ways to format strings in Python, ordered from oldest to newest.

Old Style String Formatting using Operator

This is the oldest method, inherited from C's printf. It's less common in modern Python but you might see it in older code.

  • %s is a placeholder for a string.
  • %d is a placeholder for an integer.
  • %f is a placeholder for a floating-point number.
name = "Bob"
age = 25
pi = 3.14159
# Use % to map variables to placeholders
# Note the comma for a single variable tuple: (name,)
message = "Hello, %s. You are %d years old. Pi is approx %f." % (name, age, pi)
print(message)
# Output: Hello, Bob. You are 25 years old. Pi is approx 3.141590.

To format numbers, you can add precision after the

# Format to 2 decimal places
formatted_pi = "Pi is %.2f" % pi
print(formatted_pi)
# Output: Pi is 3.14

The str.format() Method

This is a significant improvement over the operator. It's more powerful and flexible. You use curly braces as placeholders.

name = "Charlie"
age = 35
product = "Advanced Python"
# The variables are passed into the format() method
message = "Hello, {}. You are {} years old. Here is your {}.".format(name, age, product)
print(message)
# Output: Hello, Charlie. You are 35 years old. Here is your Advanced Python.

Key Features of str.format():

  • Referencing by Index: You can specify the order of arguments.

    # {0} refers to the first argument, {1} to the second, etc.
    message = "Hello, {0}. You are {1} years old. Here is your {2}.".format(name, age, product)
  • Referencing by Keyword: This makes the code much more readable.

    message = "Hello, {n}. You are {a} years old. Here is your {p}.".format(n=name, a=age, p=product)
  • Formatting Numbers: You can add formatting options inside the braces.

    price = 4999.99
    # Format with commas for thousands and 2 decimal places
    formatted_price = "The price is ${:,.2f}".format(price)
    print(formatted_price)
    # Output: The price is $4,999.99

Formatted String Literals (f-strings) - The Modern Way

Introduced in Python 3.6, f-strings are now the preferred method. They are evaluated at runtime, making them very fast. The syntax is clean and easy to read.

Simply prefix the string with an f or F and place your variables or expressions directly inside curly braces .

name = "Diana"
age = 28
product = "f-string Masterclass"
message = f"Hello, {name}. You are {age} years old. Here is your {product}."
print(message)
# Output: Hello, Diana. You are 28 years old. Here is your f-string Masterclass.

Key Features of f-strings:

  • Readability: The code looks almost like natural language.

  • Expressions: You can put any valid Python expression inside the braces, not just variable names.

    a = 10
    b = 20
    print(f"The sum of {a} and {b} is {a + b}.")
    # Output: The sum of 10 and 20 is 30.
    name = "Eve"
    print(f"Next year, {name} will be {age + 1} years old.")
    # Output: Next year, Eve will be 29 years old.
  • Formatting Numbers: Use a colon inside the braces to specify formatting, just like in str.format().

    pi = 3.14159
    # Format to 2 decimal places
    print(f"Pi is {pi:.2f}")
    # Output: Pi is 3.14
    # Format with commas for thousands
    large_number = 1234567
    print(f"The population is {large_number:,}")
    # Output: The population is 1,234,567
  • Debugging: A useful trick is to add an equals sign after the expression. It will print the expression, its value, and an equals sign.

    name = "Frank"
    age = 40
    print(f"{name=}, {age=}")
    # Output: name='Frank', age=40
    print(f"{age + 5=}")
    # Output: age + 5=45

"And" Other Formatting Operations

The phrase "format and" can also refer to formatting other data types, not just strings.

Formatting Numbers for Output

This is a common use case for all string formatting methods.

Method Example Output
f-string f"{12345:,.2f}" '12,345.00'
str.format() "{:,.2f}".format(12345) '12,345.00'
"%.2f" % 12345 '12345.00' (no comma)

Common Formatting Specifiers:

  • - Starts the format specifier.
  • - Separates the precision (number of decimal places).
  • f - Fixed-point notation.
  • d - Integer notation.
  • - Add comma as a thousands separator.
  • - Percentage (multiplies by 100).
  • e - Exponential notation.
percentage = 0.875
print(f"As a percentage: {percentage:.1%}")
# Output: As a percentage: 87.5%

Pretty-Printing JSON and Dictionaries

The json module has a built-in dump and dumps function to format JSON data with indentation.

import json
data = {
    "name": "Grace",
    "age": 50,
    "skills": ["Python", "Data Analysis", "Machine Learning"],
    "is_active": True
}
# dumps() returns a formatted string
# indent=4 adds 4 spaces of indentation
pretty_json_string = json.dumps(data, indent=4)
print(pretty_json_string)

Output:

{
    "name": "Grace",
    "age": 50,
    "skills": [
        "Python",
        "Data Analysis",
        "Machine Learning"
    ],
    "is_active": true
}

Formatting Dates and Times

The datetime module is essential for working with dates and times.

from datetime import datetime
now = datetime.now()
# Format a date and time object into a string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
# Output: 2025-10-27 15:30:00 (example output)
# Common format codes:
# %Y - Year with century (e.g., 2025)
# %m - Month as a zero-padded decimal number (01, 02, ..., 12)
# %d - Day of the month as a zero-padded decimal number (01, 02, ..., 31)
# %H - Hour (24-hour clock) as a zero-padded decimal number (00, 01, ..., 23)
# %M - Minute as a zero-padded decimal number (00, 01, ..., 59)
# %S - Second as a zero-padded decimal number (00, 01, ..., 59)

Summary and Recommendation

Method Python Version Readability Performance Recommendation
operator All Poor Good Avoid in new code. Only for legacy maintenance.
str.format() 6+ Good Good A solid, flexible choice. Great for complex cases.
f-strings 6+ Excellent Excellent The modern standard. Use this for all new Python code.

Final advice: Use f-strings for all your string formatting needs in modern Python. They are the most readable, concise, and performant option. Use json.dumps() for pretty-printing JSON and datetime.strftime() for formatting dates.

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