Python格式化输出之format用法详解
Python中格式化字符串目前有两种阵营:%和format,这篇文章主要给大家介绍了关于Python格式化输出之format用法的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
目录
format用法
一、填充
1.无参(1)
2.无参(2)
3.无参(3)
4.key value
5.列表
6.字典
7.类
8.魔法参数
二、数字格式化
三、叹号用法
总结
format用法
相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’
使用方法由两种:b.format(a)和format(a,b)。
一、填充
1.无参(1)
1 | print ( '{} {}' . format ( 'hello' , 'world' )) |
hello world
2.无参(2)
1 | print ( '{0} {1}' . format ( 'hello' , 'world' )) |
hello world
3.无参(3)
1 | print ( '{1} {0} {1}' . format ( 'hello' , 'world' )) |
world hello world
4.key value
1 | print ( 'ID:{id},Name:{name}' . format ( id = '001' ,name = 'hello' )) |
ID:001,Name:hello
5.列表
1 2 3 | 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.字典
1 2 3 | 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.类
1 2 3 4 | 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。
1 2 3 | 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) | 0xb | 0x式十六进制+小写 |
11 | ‘{:#X}’.format(11) | 0xB | 0x式十六进制+大写 |
三、叹号用法
1 2 3 | print (‘{!s}好 '.format(‘你' )) print (‘{!r}好 '.format(‘你' )) print (‘{!a}好 '.format(‘你' )) |
你好
’你’好
’\u4f60’好
!后面可以加s r a 分别对应str() repr() ascii() 作用是在填充前先用对应的函数来处理参数
差别就是
str()是面向用户的,目的是可读性,
repr()带有引号,
ascii()是面向Python解析器的,返回值表示在python内部的含义,ascii (),返回ascii编码
总结
到此这篇关于Python格式化输出之format用法的文章就介绍到这了
原文链接:https://blog.csdn.net/weixin_43347550/article/details/105004905