Python技巧之内置函数 format()

✨ 在 Python 中,format() 是一个内置函数,用于格式化字符串。它提供了灵活的方式来将变量插入到字符串中,并控制它们的显示格式。

一、format() 函数概述

format() 函数是 Python 的内置函数之一,用于字符串格式化。它的语法如下:

format(value, format_spec)

其中,参数说明如下:

  • value: 要格式化的值。
  • format_spec: 格式化规范,用于指定值的显示方式。

format() 函数返回一个格式化后的字符串。

二、format() 函数的用法

1. 基本用法

#🌾:定义变量
name = 'Alice'
age = 30
#🌾:定义格式
message = "My name is {} and I am {} years old.".format(name,age)
#🌾:输出
print(message) # My name is Alice and I am 30 years old.

在以上示例中,我们使用 format() 函数将变量 name 和 age 插入到字符串中进行格式化。

2. 格式化数字

#🌾:定义变量
num = 123.456
#🌾:定义格式
formatted_num = "{:.2f}".format(num)
#🌾:输出
print(formatted_num) #输出:123.46

在以上示例中,我们使用 format() 函数对数字进行格式化,保留两位小数。

3. 格式化日期时间

from datetime import datetime

#🌾:定义变量
now = datetime.now()
#🌾:定义格式
formatted_date = "{:%Y-%m-%d %H:%M:%S}".format(now)
#🌾:输出
print(formatted_date) # 输出:2024-12-20 14:32:39

在以上示例中,我们使用 format() 函数格式化当前日期时间。

三、format() 函数的高级用法

1. 对齐和填充

#🌾 定义变量
name = 'Alice'
age = 30
#🌾 定义格式
formatted_str = "{:<10} {:>3}".format(name,age)
#🌾 输出
print(formatted_str) 

在以上示例中,我们使用 format() 函数对字符串进行左对齐和右对齐,并指定宽度。

2. 格式化字典

#🌾 变量
person = {"name": "Bob", "age": 25}
#🌾 定义格式
formatted_str = "Name: {name}, Age: {age}".format(**person)
#🌾 输出
print(formatted_str) # 输出:Name: Bob, Age: 25

在以上示例中,我们使用 format() 函数格式化字典中的键值对。

四、注意事项

在使用 format() 函数时,要注意格式化规范的使用,确保符合要求的格式。

可以在格式化规范中使用各种选项,如对齐、填充、精度等,以满足不同的需求。

posted on 2024-12-20 14:40  梁飞宇  阅读(171)  评论(0)    收藏  举报