Python格式化函數format詳解

  • 2020 年 2 月 11 日
  • 筆記

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