Hello 大家好,我是一名新来的金融领域打工人,日常分享一些python知识,都是自己在学习生活中遇到的一些问题,分享给大家,希望对大家有一定的帮助!
今天给大家讲讲曾经困扰我很久的字符串格式化其中的format格式的设置问题,其中包括小数点设置、百分号设置以及科学计数法等的设置,下面我们直接上代码:
下面的例句我使用的是一段话,包含一个数字的字符串格式化的形式:
1.小数点位数设置
print('value of the European call option is {:.3f}.'.format(3.1415926))
## value of the European call option is 3.142. ## 保留小数点后三位
print('value of the European call option is {:+.3f}.'.format(3.1415926))
## value of the European call option is +3.142. ## 带符号保留小数点后三位
print('value of the European call option is {:.3f}.'.format(-3.1415926))
## value of the European call option is -3.142. ## 保留小数点后三位
print('value of the European call option is {:.0f}.'.format(3.1415926))
## value of the European call option is 3. ## 不保留小数点
2.数据填充设置
print('value of the European call option is {:0>2d}.'.format(3))
## value of the European call option is 03. ## 用0填充数字左侧 宽度为2
print('value of the European call option is {:0>3d}.'.format(3))
## value of the European call option is 003. ## 填充数字左侧 宽度为3
print('value of the European call option is {:0<2d}.'.format(3))
## value of the European call option is 30. ## 填充数字右侧 宽度为2
print('value of the European call option is {:0<3d}.'.format(3))
## value of the European call option is 300. ## 填充数字右侧 宽度为3
print('value of the European call option is {:0<4d}.'.format(3))
## value of the European call option is 3000. ## 填充数字右侧 宽度为4
3.逗号分隔、百分比、科学计数法设置
print('value of the European call option is {:,}.'.format(3000000))
## value of the European call option is 3,000,000. ## 以逗号分隔数字
print('value of the European call option is {:.2%}.'.format(3.1415926))
## value of the European call option is 314.16%. ## 百分比格式
print('value of the European call option is {:.2e}.'.format(31.415926))
## value of the European call option is 3.14e+01. ## 科学计数法
4.数字对齐显示的设置
print('value of the European call option is {:>10d}.'.format(3))
## value of the European call option is 3. ## 填充数字左侧 宽度为10(右对齐)
print('value of the European call option is {:<10d}.'.format(3))
## value of the European call option is 3 . ## 填充数字右侧 宽度为10(左对齐)
print('value of the European call option is {:^10d}.'.format(3))
## value of the European call option is 3 . ## 中间对齐
在format进行格式设置的时候常用的比如小数点位数、百分比、科学计数法以及文本对齐等等常用的设置,希望大家在平时的使用中多加注意!
好啦,今天的小知识就分享到这里啦!



