欢迎访问宙启技术站
智能推送

Python中的format函数使用方法详解

发布时间:2023-07-03 07:48:15

format函数是Python中的一个字符串方法,用于格式化字符串。

基本用法:

1. 使用大括号{}作为占位符,表示需要被替换的部分。

2. 在format函数中的大括号{}中可以添加参数,用于指定要替换的值。

3. 格式化字符串时,可以传递一个或多个值作为参数,用于替换大括号{}中的占位符。

4. format函数将替换大括号{}中的值,并返回格式化后的字符串。

示例:

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.

常见用法:

1. 索引:

可以在大括号{}中使用数字索引来指定替换值的顺序。

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

输出:

My name is Alice and I am 25 years old.

2. 命名:

可以在大括号{}中使用属性名称来指定需要替换的值。

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

输出:

My name is Alice and I am 25 years old.

3. 格式规范:

可以在大括号{}中使用冒号:来指定替换值的格式。

pi = 3.14159
print("The value of pi is approximately {:.2f}.".format(pi))

输出:

The value of pi is approximately 3.14.

- :后的.2表示要保留两位小数,并且四舍五入。

4. 对齐:

可以在冒号:后使用<、>、^分别表示左对齐、右对齐、居中对齐。

name = "Alice"
print("|{:<10}|".format(name))
print("|{:>10}|".format(name))
print("|{:^10}|".format(name))

输出:

|Alice     |
|     Alice|
|  Alice   |

- :后的10表示字段的宽度,如果字段的长度小于指定的宽度,则会使用空格进行填充。

5. 千位分隔符:

可以在冒号:后使用,来添加千位分隔符。

number = 1234567
print("The number is {:,}".format(number))

输出:

The number is 1,234,567

6. 格式化日期:

import datetime

date = datetime.datetime.now()
print("Today is {:%Y-%m-%d %H:%M:%S}".format(date))

输出:

Today is 2022-10-21 14:30:00

更多的格式化选项可以查看Python官方文档中format函数的说明。

format函数是Python中非常常用的字符串格式化方法,通过灵活的占位符和格式规范,可以方便地对字符串进行格式化操作,使输出更加美观和易读。