前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python格式化函数format详解

Python格式化函数format详解

作者头像
王大力测试进阶之路
发布2020-02-11 10:11:46
6540
发布2020-02-11 10:11:46
举报
文章被收录于专栏:橙子探索测试橙子探索测试

format用法

相对基本格式化输出采用‘%’的方法,format()功能更强大,该函数把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’使用方法由两种:b.format(a)和format(a,b) format 函数可以接受不限个参数,位置可以不按顺序

1、不带编号,即“{}”

print('{} {}'.format('hello','world'))# 不设置指定位置,按默认顺序

#hello world

2、带数字编号,可调换顺序,即“{1}”、“{2}”

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

#hello hello

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

#hello world

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

#world hello

print('{0} {0}'.format('hello'))

#hello hello

3、带关键字,即“{a}”、“{tom}”

print('{x} {y}'.format(x='hello',y='world'))

#hello world

4、通过映射 list

list a_list = ['chuhao',20,'china']

print('my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list))

#my name is chuhao,from china,age is 20

5、通过映射dict

dict b_dict = {'name':'chuhao','age':20,'province':'shanxi'}

print('my name is {name}, age is {age},from {province}'.format(**b_dict))

#my name is chuhao, age is 20,from shanxi

6、传入对象

class AssignValue(object):

def __init__(self, value):

self.value = value

my_value = AssignValue(6)

print('value 为: {0.value}'.format(my_value))

#value 为: 6

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 橙子探索测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档