转载:Python 内建函数列表 > Python 的内置函数 format
def format(value, format_spec=''):
'''
类型转换为 format
:param value: 一个变量
:param format_spec: 格式
:return: 转换为 format 后的值
'''
示例:
# 数字格式化
print(format(3.14159, ".2f")) # 输出: '3.14'
print(format(1000000, ",")) # 输出: '1,000,000'
# 对齐和填充
print(format("hello", "^10")) # 输出: ' hello ' (居中对齐,宽度10)
print(format(42, "05d")) # 输出: '00042' (用0填充,宽度5)
# 进制转换
print(format(10, "b")) # 输出: '1010' (二进制)
print(format(255, "x")) # 输出: 'ff' (十六进制小写)
参考: