字符串格式化之format
来源:互联网 发布:ftp断点下载 java 编辑:程序博客网 时间:2024/06/06 02:20
format用法:
1.使用位置穿参
5、使用索引利用{}代替了%的位置穿参
>>> l1 = ["中国移动","10086"]>>> a = '{}服务热线为{}'.format('中国移动', '10086')>>> b = '{}服务热线为{}'.format('10086', '中国移动')>>> c = '{1}服务热线为{0}'.format('10086', '中国移动')>>> d = '{0}服务热线为{1}'.format('10086', '中国移动')>>> f = '{1}服务热线为{0}'.format(*l1)>>> a'中国移动服务热线为10086'>>> b'10086服务热线为中国移动'>>> c'中国移动服务热线为10086'>>> d'10086服务热线为中国移动'>>> f'10086服务热线为中国移动'2.关键字穿参
关键字参数要一一对应 可用字典当关键字参数传入值,字典前加**即可
>>> hash = {'name':'hoho','age':18}>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)'my name is hoho,age is 19'>>> 'my name is {name},age is {age}'.format(**hash)'my name is hoho,age is 18'
3、填充与格式化
:[填充字符][对齐方式 <^>][宽度]
>>> '{0:*>10}'.format(10) ##右对齐'********10'>>> '{0:*<10}'.format(10) ##左对齐'10********'>>> '{0:*^10}'.format(10) ##居中对齐'****10****'
4、精度与进制
>>> '{0:.2f}'.format(1/3)'0.33'>>> '{0:b}'.format(10) #二进制'1010'>>> '{0:o}'.format(10) #八进制'12'>>> '{0:x}'.format(10) #16进制'a'>>> '{:,}'.format(12369132698) #千分位格式化'12,369,132,698'
5、使用索引
>>> li['hoho', 18]>>> 'name is {0[0]} age is {0[1]}'.format(li)'name is hoho age is 18
5、使用索引
阅读全文