测试format的不同用法
# 格式化{{}} 等于{} print('{{ hello {0} }}'.format('Kevin')) # { hello Kevin } # test 同一个参数指定多个位置 print('\n 同一个参数多个位置调用') print('Hi, I am {0}, my {1} is {0}'.format('jimmy', 'name')) # Hi, I am jimmy, my name is jimmy # 对齐与填充 print('\n 对齐与填充') import math print('{:o<10}'.format(12345)) # 12345ooooo 左对齐 填充o 宽度10 print('{:x>20.15f}'.format(math.pi)) # xxx3.141592653589793 右对齐 填充x 保留小数15 宽度20 print('{:x> 20.15f}'.format(math.pi)) # xx 3.141592653589793 右对齐 填充x 保留小数15 宽度20 print('{:x>+20.15f}'.format(math.pi)) # xx+3.141592653589793 右对齐 填充x 保留小数15 宽度20 print('{:x>+20.15f}'.format(-3.141592653589793111)) # xx-3.141592653589793 右对齐 填充x 保留小数15 宽度20 print('{:+^10d}'.format(123)) # +++123++++ 中间对齐 填充+ 宽度10 print('{:,}'.format(1234567890)) # 1,234,567,890 以逗号分隔的数字格式 print('{:.2%}'.format(0.1)) # 10.00% 百分比格式 保留小数2 # 通过字典设置参数 print('\n 通过字典调用') dict2 = {'name': 'jimmy', 'gender': 'male'} print('my name is: {name}, gender is {gender}'.format(**dict2)) # 注意需要两个**在字典之前 my name is: jimmy, gender is male print('name:{d[name]}, gender:{d[gender]}'.format(d=dict2)) # 赋值给d name:jimmy, gender:male print('\n 序列化字典的输出') dict1 = {'jimmy': 100, 'tom': 88, 'penny': 99} for en, (k, v) in enumerate(dict1.items(),1): # 把每一个 item 绑定序号, enumerate([迭代器], [开始的号码]) print('NO:{{{}}} ---- name: {:<6} score: {:>3}'.format(en, k, v)) # NO:{1} ---- name: jimmy score: 100 # NO:{2} ---- name: tom score: 88 # NO:{3} ---- name: penny score: 99 # 调用类的属性和方法 print('\n 调用类的属性方法') class Teacher(): job = 'teacher' def speak(self): return 'good good study!!!' print('as a {t.job}, I have to talk you that {t.speak}'.format(t=Teacher())) # 无法在{}里面调用 类的方法 # as a teacher, I have to talk you that <bound method Teacher.speak of <__main__.Teacher object at 0x000002057CC8A240>> print('as a {}, I have to talk you that {}'.format(Teacher().job, Teacher().speak())) # 无法调用 类的方法 # as a teacher, I have to talk you that good good study!!! # 魔法参数 print('\n 魔法参数') args = ['jimmy', 'penny'] kwargs = {'name1': 'jack', 'name2': 'king'} print("this is {1} calling, I want to speak with {name2}, tell him {0} married with {name1}".format(*args, **kwargs)) # this is penny calling, I want to speak with king, tell him jimmy married with jack # 调用函数 print('\n 调用函数') def speak(): return 'do you think am I' print('{} very good?'.format(speak())) # do you think am I very good? # 设置格式 print('\n 设置格式') text1 = 'I feel good' text1_formated = '{:-^30}'.format(text1) print(text1_formated) # ---------I feel good---------- text1_formated2 = '{:=^50}'.format(text1_formated) print(text1_formated2) # ==========---------I feel good----------========== # 浓缩一下 def text_formater(text): text_formated = '{:=^50} '.format(' {:-^30} '.format(' ' + str(text) + ' ')) print(text_formated) text_formater('Tile 123') # ========= ---------- Tile 123 ---------- =========