python什么是格式化
本文总结一下python格式化文本的方法,需要的小伙伴可以参考。
1、首先看使用%格式化文本
常见的占位符:
常见的占位符有:
%d整数
%f浮点数
%s字符串
%x十六进制整数
使用方法
>>>'Hello,%s'%'world'
'Hello,world'
>>>'Hi,%s,youhave$%d.'%('Michael',1000000)
'Hi,Michael,youhave$1000000.'
使用的时候不知道写什么的地方直接使用%s进行代替,语句的末尾加上%()括号里面直接填写内容即可(字符串加上引号,中间用“,”分割),如果只有一个%?,括号可以省略。
高级一点的用法:
格式化整数指定是否补零:
首先看代码:
>>>'%d-%d'%(3,23)
'3-23'
>>>'%2d-%2d'%(3,23)
'3-23'
>>>'%3d-%3d'%(3,23)
'3-23'
>>>'%4d-%4d'%(3,23)
'3-23'
>>>'%01d-%01d'%(3,23)
'3-23'
>>>'%02d-%02d'%(3,23)
'03-23'
>>>'%03d-%03d'%(3,23)
'003-023'
>>>'%04d-%04d'%(3,23)
'0003-0023'
>>>
可以看得出来,d前面的数字用来指定占位符,表示被格式化的数值占用的位置数量(字节还是什么不知道这样的表述是否正确),指定之后比如%3d,代表这个整数要占用3个位置,前面如果有0代表占用的地方使用0补齐,没有就使用空格补齐。指定的空间位置小于实际的数字大小,以实际占用的位置大小为准。
指定小数的位数:
>>>'%.f'%3.1415926
'3'
>>>'%.1f'%3.1415926
'3.1'
>>>'%.2f'%3.1415926
'3.14'
>>>'%.3f'%3.1415926
'3.142'
>>>
可以看出.后面的数字用来表示保留的小数点的位数,".1"代表保留小数点后面一位小数。
如果不确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串:
>>>'Age:%s.Gender:%s'%(25,True)
'Age:25.Gender:True'
有些时候,字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%:
>>>'growthrate:%d%%'%7
'growthrate:7%'
尝试使用其他方法对%进行转义,但是好像没有用,有什么其他方法欢迎评论。
2、使用format方法进行格式化
代码演示:
age=25
name='Swaroop'
print('{0}is{1}yearsold'.format(name,age))
print('Whyis{0}playingwiththatpython?'.format(name))
位置使用{1}按照使用的顺序写好,后面格式使用.format()写好对应的参数即可。
输出结果:
Swaroopis25yearsold
WhyisSwaroopplayingwiththatpython?
其实也可以使用第一种方法实现:
age=25
name='Swaroop'
print('%sis%syearsold'%(name,age))
print('Whyis%splayingwiththatpython?'%(name))
输出
Swaroopis25yearsold
WhyisSwaroopplayingwiththatpython?
实现的结果都是一样的。
以上内容为大家介绍了python培训之什么是格式化,希望对大家有所帮助,如果想要了解更多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热门推荐
技术干货






