pyhton中format函数用法
程序员文章站
2022-04-04 21:17:43
...
从代码中看其使用方法:
#通过位置
print('{0},{1}'.format('csdn',20))
print ('{},{}'.format('csdn',20))
print ('{1},{0},{1}'.format('csdn',20))
#通过关键字参数
print('{name},{age}'.format(age=18,name='csdn'))
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return 'This guy is {self.name},is {self.age} old'.format(self=self)
print (str(Person('csdn',18)))
#通过映射 list
a_list = ['csdn',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
#通过映射 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
#填充与对齐
print ('{:>8}'.format('234'))
# 189
print ('{:0>8}'.format('234'))
#00000189
print ('{:a>8}'.format('234'))
#aaaaa189
#精度与类型f
#保留两位小数
print ('{:.2f}'.format(321.33345))
#321.33
#用来做金额的千位分隔符
print ('{:,}'.format(1234567890))
#1,234,567,890
#其他类型 主要就是进制了,b、d、o、x分别是二进制、十进制、八进制、十六进制。
print('{:b}'.format(18) )#二进制 10010)
运行结果:
csdn,20
csdn,20
20,csdn,20
csdn,18
This guy is csdn,is 18 old
my name is csdn,from china,age is 20
my name is chuhao, age is 20,from shanxi
234
00000234
aaaaa234
321.33
1,234,567,890
10010
上一篇: JavaScript函数的定义
下一篇: HTML5新增核心工具——canvas