一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python格式化输出之format用法代码

时间:2022-01-19 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python格式化输出之format用法代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

format用法

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’

使用方法由两种:b.format(a)和format(a,b)。

一、填充

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.

二、数字格式化

三、叹号用法

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

你好

’你’好

’u4f60’好

!后面可以加s r a 分别对应str() repr() ascii() 作用是在填充前先用对应的函数来处理参数

差别就是

str()是面向用户的,目的是可读性,

repr()带有引号,

ascii()是面向Python解析器的,返回值表示在python内部的含义,ascii (),返回ascii编码

热门栏目