如何使用format函數(shù)格式化字符串

小樊
81
2024-09-21 05:44:41
欄目: 編程語言

在Python中,可以使用format()函數(shù)來格式化字符串。format()函數(shù)可以接受任意數(shù)量的參數(shù),并且可以使用占位符{}來表示需要被替換的部分。

以下是一些使用format()函數(shù)的示例:

  1. 格式化整數(shù)和浮點(diǎn)數(shù):
x = 123
y = 456.789
print("x = {}, y = {:.2f}".format(x, y))

輸出:x = 123, y = 456.79 2. 格式化字符串:

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

輸出:My name is Alice and I am 25 years old. 3. 格式化日期和時(shí)間:

from datetime import datetime

now = datetime.now()
print("Today is {}.".format(now.strftime("%Y-%m-%d")))

輸出:Today is 2023-07-06.(注意:實(shí)際輸出取決于當(dāng)前日期) 4. 使用位置參數(shù):

print("Hello, {}! Today is {}.".format("Alice", "Monday"))

輸出:Hello, Alice! Today is Monday. 5. 使用關(guān)鍵字參數(shù):

print("Hello, {person}! Today is {day}.".format(person="Bob", day="Tuesday"))

輸出:Hello, Bob! Today is Tuesday.

這些示例展示了如何使用format()函數(shù)來格式化不同類型的變量和常量。通過使用占位符{}和適當(dāng)?shù)母袷秸f明符,可以創(chuàng)建格式化的字符串,以便更清晰、易讀地顯示數(shù)據(jù)。

0