python中format所有用法
python,format,所有,用法
2025-04-01 16:27:56 时间
大家好,又见面了,我是你们的朋友全栈君。
平时只用参数匹配,偶尔看到别人的format用法楞住没反应过来,遂记下
#通过位置
print '{0},{1}'.format('hehe',20)
print '{},{}'.format('hehe',20)
print '{1},{0},{1}'.format('hehe',20)
#通过关键字参数
print '{name},{age}'.format(age=18,name='hehe')
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return 'This guy is {self.name},is {self.age} old'.format(self=self)
print str(Person('hehe',18))
#通过映射 list
a_list = ['hehe,20,'china']
print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)
#my name is hehe,from china,age is 20
#通过映射 dict
b_dict = {'name':'hehe','age':20,'province':'shanxi'}
print 'my name is {name}, age is {age},from {province}'.format(**b_dict)
#my name is hehe, age is 20,from shanxi
#填充与对齐
print '{:>8}'.format('189')
# 189
print '{:0>8}'.format('189')
#00000189
print '{:a>8}'.format('189')
#aaaaa189
#精度与类型f
#保留两位小数
print '{:.2f}'.format(321.33345)
#321.33
#用来做金额的千位分隔符
print '{:,}'.format(1234567890)
#1,234,567,890
#其他类型 主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。
print '{:b}'.format(18) #二进制 10010
print '{:d}'.format(18) #十进制 18
print '{:o}'.format(18) #八进制 22
print '{:x}'.format(18) #十六进制12
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/155850.html原文链接:https://javaforall.cn
相关文章
- 使用Python验证并利用Redis未授权漏洞
- CPD 算法实现点云配准(python版本)[通俗易懂]
- python分子化学模拟_#分子模拟#MDTraj分子模拟python包(一)
- 2022年最新Python大数据之Python基础【九】面向对象与继承
- Python:Flask使用jsonify格式化时间
- 【过程记录】python环境离线迁移
- 自动编码器重建图像及Python实现
- Python-基础03-流程控制
- Python人员信息管理系统(当期末作业)
- 超强 Python 数据可视化库,一文全解析
- Python-基础02-程序与用户交互
- Python 学生信息管理系统——文章中源码100%真实有效—–如何将类、初始化属性、模块、循环判断、静态方法等一系列知识点结合起来做一个项目「建议收藏」
- 5分钟NLP:Python文本生成的Beam Search解码
- python中字符转换
- Python怎么输入小数和整数_python输入非负整数
- Python每日一练(六)
- Python项目46-xadmin管理后台数据(强撸)
- python 获取时间戳_datetime获取当前时间
- python 画图命令[通俗易懂]
- python电脑版微信-微信PC版的API接口 | 可通过Python调用微信功能