format()
方法根据指定的格式化器返回一个格式化的值。
示例
value = 45
# format the integer to binary
binary_value = format(value, 'b')
print(binary_value)
# Output: 101101
format() 语法
format(value, format_spec)
format() 参数
该函数接受两个参数
- value - 我们要格式化的数据
- format_spec - 关于如何格式化数据的规范
format() 返回值
format()
函数以所需格式的字符串表示形式返回一个值。
示例:使用 format() 进行数字格式化
# decimal formatting
decimal_value = format(123, 'd')
print("Decimal Formatting:", decimal_value)
# binary formatting
binary_value = format(123, 'b')
print("Binary Formatting:", binary_value)
输出
Decimal Formatting: 123 Binary Formatting: 1111011
这里,format(123, 'd')
和 format(123, 'b')
将整数 123 分别转换为其十进制和二进制字符串表示形式。
注意:我们使用了格式说明符,d
用于十进制,b
用于二进制。要了解有关格式类型的更多信息,请访问格式类型。
带对齐和宽度的数字格式化
格式化中的对齐是指数字在可用空间中的定位或放置方式,它决定了数字相对于该空间的起始和结束位置。
它控制数字在指定区域内的视觉呈现方式。
对齐选项
对齐 | 描述 |
---|---|
左对齐 < |
将输出字符串左对齐 |
右对齐 > |
将输出字符串右对齐 |
居中对齐 ^ |
将输出字符串居中对齐到剩余空间的中心 |
让我们看一个例子。
# formatting numbers without specifying width
no_width = format(123, 'd')
print("Without specified width:", no_width)
# formatting number with a width of 10, right-aligned
right_aligned = format(123, '>10d')
print("Right-aligned with width 10:", right_aligned)
# formatting number with a width of 10, left-aligned
left_aligned = format(123, '<10d')
print("Left-aligned with width 10:", left_aligned)
# formatting number with a width of 10, center-aligned
center_aligned = format(123, '^10d')
print("Center-aligned with width 10:", center_aligned)
输出
Without specified width: 123 Right-aligned with width 10: 123 Left-aligned with width 10: 123 Center-aligned with width 10: 123
这里,
format(123, 'd')
- 数字在没有指定宽度的情况下进行格式化。format(123, '>10d')
- 数字在 10 个字符宽度的范围内右对齐,左侧有额外的空格。format(123, '<10d')
- 数字在 10 个字符宽度的范围内左对齐,右侧有额外的空格。format(123, '^10d')
- 数字在 10 个字符宽度的范围内居中对齐,两侧均匀分布额外的空格。
示例:带符号的数字格式化
# using '+' and '-' format specifier
positive_with_plus = format(123, '+')
positive_with_minus = format(123, '-')
print("Positive with '+':", positive_with_plus)
print("Positive with '-':", positive_with_minus)
输出
Positive with '+': +123 Positive with '-': 123
在上面的示例中,我们使用每个符号选项格式化了数字 123 和 -123。
格式化中的符号选项控制数字符号的显示。这里,+
表示正数和负数都会显示其符号。
注意:符号选项 -
表示只有负数会显示其符号,而 ' '
将对正数显示一个空格,对负数显示一个减号。
示例:带精度的数字格式化
精度允许我们定义小数点后显示的位数。例如,
# set precision to 2 for floating-point number
precision_value = format(123.4567, '.2f')
print(precision_value)
# Output: 123.46
这里,.2f
表示小数点后将显示两位数字。
另请阅读