栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python金融分析小知识(18)——字符串格式化之format格式设置

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python金融分析小知识(18)——字符串格式化之format格式设置

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进行格式设置的时候常用的比如小数点位数、百分比、科学计数法以及文本对齐等等常用的设置,希望大家在平时的使用中多加注意!

好啦,今天的小知识就分享到这里啦!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/918059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号