温馨提示×

如何使用format函数格式化字符串

小樊
81
2024-09-21 05:44:41
栏目: 编程语言

在Python中,可以使用format()函数来格式化字符串。format()函数可以接受任意数量的参数,并且可以使用占位符{}来表示需要被替换的部分。

以下是一些使用format()函数的示例:

  1. 格式化整数和浮点数:
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. 格式化日期和时间:

from datetime import datetime

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

输出:Today is 2023-07-06.(注意:实际输出取决于当前日期) 4. 使用位置参数:

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

输出:Hello, Alice! Today is Monday. 5. 使用关键字参数:

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

输出:Hello, Bob! Today is Tuesday.

这些示例展示了如何使用format()函数来格式化不同类型的变量和常量。通过使用占位符{}和适当的格式说明符,可以创建格式化的字符串,以便更清晰、易读地显示数据。

0