8 - 格式化整数和浮点数
原创
©著作权归作者所有:来自51CTO博客作者小小猿若尘的原创作品,请联系作者获取转载授权,否则将追究法律责任
整数格式化
- 请格式化一个整数,按10位输出,不足10位前面补0
n = 1234
print(format(n, '10d'))
# 左侧补零
print(format(n, '0>10d'))
# 右侧补零
print(format(n, '0<10d'))
浮点数格式化
x1 = 1234.5678
x2 = 58.1
# 保留小数点后两位
print(format(x1, '0.2f'))
print(format(x2, '0.2f'))
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 字符串操作