整数格式化

  • 请格式化一个整数,按10位输出,不足10位前面补0
n = 1234

print(format(n, '10d'))
# 左侧补零
print(format(n, '0>10d'))
# 右侧补零
print(format(n, '0<10d'))
      1234
0000001234
1234000000

浮点数格式化

  • 格式化一个浮点数,要保留小数点两位
x1 = 1234.5678
x2 = 58.1

# 保留小数点后两位
print(format(x1, '0.2f'))
print(format(x2, '0.2f'))
1234.57
58.10

3. 请描述format 函数的主要用法

# format 函数用于格式化数值,通过第二个参数指定格式化规则

# 右对齐
print(format(x2, '*>12.2f'))

# 左对齐
print(format(x2, '*<12.2f'))

# 中心对齐
print(format(x2, '*^12.2f'))

# 用千位号分割
print(format(123455678, ','))

# 整数用','分割,并保留小数点后两位
print(format(123456.12321, ',.2f'))

# 按科学计数法输出
print(format(x1, 'e'))

# 保留小数点后两位,科学计数法输出
print(format(x1, '0.2E'))
*******58.10
58.10*******
***58.10****
123,455,678
123,456.12
1.234568e+03
1.23E+03

​9 - python 字符串操作​