Python之format用法详解

一、填充

1.无参(1)

print('{} {}'.format('hello','world'))

hello world

2.无参(2)

print('{0} {1}'.format('hello','world'))

hello world

3.无参(3)

print('{1} {0} {1}'.format('hello','world'))

world hello world

4.key value

print('ID:{id},Name:{name}'.format(id='001',name='hello'))

ID:001,Name:hello

5.列表

list=['001','hello']
print('ID:{List[0]},Name:{List[1]}'.format(List = list))
print('ID:{0[0]},Name:{0[1]}'.format(list))

ID:001,Name:hello
ID:001,Name:hello

6.字典

dict={'id':'001,'name':'hello'}
print('ID:{Dict[0]},Name:{Dict[1]}'.format(Dict = dict))
print('ID:{id},Name:{name}'.format(**dict))

ID:001,Name:hello
ID:001,Name:hello

7.类

class value():
	id = '001'
	name = 'hello'
print('ID:{Value.id},Name{Value.name}'.format(Value = value))

ID:001,Name:hello

8.魔法参数

*args表示任何多个无名参数,它是一个tuple or list;**kwargs表示关键字参数,它是一个 dict。

args = [',','.']
kwargs = {'id': '001','name':'hello'}
print('ID:{id}{}Name:{name}{}'.format(*args, **kwargs))

ID:001,Name:hello.

二、数字格式化

数字格式输出描述
3.1415926{:.2f}3.14保留小数点后两位
3.1415926{:+.2f}+3.14带符号保留小数点后两位
-1{:+.2f}-1.00带符号保留小数点后两位
2.71828{:.0f}3不带小数
5{:0>2d}05数字补零 (填充左边, 宽度为2)
5{:x<4d}5xxx )数字补x (填充右边, 宽度为4
10{:x<4d}10xx )数字补x (填充右边, 宽度为4
1000000{:,}1,000,000以逗号分隔的数字格式
0.25{:.2%}25.00%百分比格式
1000000000{:.2e}1.00e+09指数记法
13{:>10d}13右对齐 (默认, 宽度为10)
13{:<10d}13左对齐 (宽度为10)
13{:^10d}13中间对齐 (宽度为10)
11‘{:b}’.format(11)1011二进制
11‘{:d}’.format(11)11十进制
11‘{:o}’.format(11)13八进制 //这里打成中文的冒号了,因为用英文的会打出一个O的表情~~~
11‘{:x}’.format(11)b十六进制
11‘{:#x}’.format(11)0xb0x式十六进制+小写
11‘{:#X}’.format(11)0xB0x式十六进制+大写

三、叹号用法

print({!s}好’.format(‘你’)) 
print({!r}好’.format(‘你’)) 
print({!a}好’.format(‘你’)) 

你好
’你’好
’\u4f60’好

!后面可以加s r a 分别对应str() repr() ascii() 作用是在填充前先用对应的函数来处理参数
差别就是
str()是面向用户的,目的是可读性,
repr()带有引号,
ascii()是面向Python解析器的,返回值表示在python内部的含义,ascii (),返回ascii编码

上一篇文章———>分治法——快速排序

下一篇文章———>《高响应比优先调度算法(HRRN)例题详解》

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐