python 的 format 函数

只愿长相守 提交于 2020-02-06 16:34:30

python的格式化字符串方法之一------------format 函数

它通过{}和:来代替%。

数字格式输出描述
3.1415926 {:.2f} 3.14 保留小数点后两位
3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
-1 {:+.2f} -1.00 带符号保留小数点后两位
2.71828 {:.0f} 3 不带小数
5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
1000000 {:,} 1,000,000 以逗号分隔的数字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00e+09 指数记法
13 {:10d}         13 右对齐 (默认, 宽度为10)
13 {:<10d} 13 左对齐 (宽度为10)
13 {:^10d}     13 中间对齐 (宽度为10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
1011
11
13
b
0xb
0XB
进制转换

如果补入的是字符,在对齐中不用加d!!!!!!!!!

用法

#通过位置
print '{0},{1}'.format('chuhao',20)

print '{},{}'.format('chuhao',20)

print '{1},{0},{1}'.format('chuhao',20)

#通过关键字参数
print '{name},{age}'.format(age=18,name='chuhao')

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('chuhao',18))

#通过映射 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

#通过映射 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

#填充与对齐  填入的是字符串,若是数字就要加d
print '{:>8}'.format('189')
#     189
print '{:0>8}'.format('189')
#00000189
print '{:a>8}'.format('189')
#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
print '{:d}'.format(18) #十进制 18
print '{:o}'.format(18) #八进制 22
print '{:x}'.format(18) #十六进制12

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!