python

format函数在python中的用法

小亿
81
2024-09-03 05:45:47
栏目: 编程语言

format() 是 Python 中的一个内置函数,用于格式化字符串。它可以接受多种类型的参数,并将它们转换为字符串。format() 函数的基本语法如下:

format(value, format_spec)

其中,value 是要格式化的值,format_spec 是格式说明符,用于指定值的格式。

以下是 format() 函数的一些常见用法:

  1. 格式化整数和浮点数:
x = 123456789
formatted_x = format(x, ',')  # 添加千位分隔符
print(formatted_x)  # 输出:123,456,789

y = 3.14159
formatted_y = format(y, '.2f')  # 保留两位小数
print(formatted_y)  # 输出:3.14
  1. 格式化字符串:
name = "Alice"
age = 30
formatted_string = format("My name is {} and I am {} years old.", name, age)
print(formatted_string)  # 输出:My name is Alice and I am 30 years old.
  1. 使用格式说明符进行更复杂的格式化:
import datetime

now = datetime.datetime.now()
formatted_date = format(now, '%Y-%m-%d %H:%M:%S')  # 格式化日期和时间
print(formatted_date)  # 输出:2022-01-01 12:34:56(根据实际时间)

注意:在上面的示例中,我们使用了大括号 {} 作为占位符。这是因为 format() 函数支持格式化字符串的新语法,称为“格式化字符串文字”或“f-string”。在 f-string 中,可以直接在字符串中使用大括号包围的变量名,而无需调用 format() 函数。例如:

name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # 输出:My name is Alice and I am 30 years old.

0
看了该问题的人还看了