pythonformat()格式化输出怎么用
python的format()方法的语法格式如下:
str.format(args)
此方法中,str用于指定字符串的显示样式;args用于指定要进行格式转换的项,如果有多项,之间有逗号进行分割。学习format()方法的难点,在于搞清楚str显示样式的书写格式。在创建显示样式模板时,需要使用{}和:来指定占位符,其完整的语法格式为:
{[index][:[[fill]align][sign][#][width][.precision][type]]}
注意,格式中用[]括起来的参数都是可选参数,即可以使用,也可以不使用。各个参数的含义如下:
index:指定:后边设置的格式要作用到args中第几个数据,数据的索引值从0开始。如果省略此选项,则会根据args中数据的先后顺序自动分配。
fill:指定空白处填充的字符。注意,当填充字符为逗号(,)且作用于整数或浮点数时,该整数(或浮点数)会以逗号分隔的形式输出,
例如(1000000会输出1,000,000)。
align:指定数据的对齐方式,
实例
#以货币形式显示
print("货币形式:{:,d}".format(1000000))
#科学计数法表示
print("科学计数法:{:E}".format(1200.12))
#以十六进制表示
print("100的十六进制:{:#x}".format(100))
#输出百分比形式
print("0.01的百分比表示:{:.0%}".format(0.01))
输出结果
货币形式:1,000,000
科学计数法:1.200120E+03
100的十六进制:0x64
0.01的百分比表示:1%
以上内容为大家介绍了python培训之format()格式化输出怎么用,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






