【Python】format格式化函数

基本语法是通过 {}: 来代替以前的 %

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

保留小数点后两位

>>> r = 3.141592
>>>> print("{:.2f}".format(r))
3.14

填充&对齐

  • <左对齐
  • >右对齐
  • ^居中对齐
  • : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
数字补x (填充左边, 宽度为5)
>>> n = 6
>>> print("{:x>5d}".format(n))
xxxx6
数字补x (填充右边, 宽度为5)
>>> n = 60
print("{:x<5d}".format(n))
60xxx
对齐 (宽度为7)
>>> n = 81
>>> print("{:<7d}".format(n))
81     
>>> print("{:>7d}".format(n))
     81
>>> print("{:^7d}".format(n))
  81   
进制

b、d、o、x 分别是二进制、十进制、八进制、十六进制。

'{:b}'.format(11) #1011
'{:d}'.format(11) #11
'{:o}'.format(11) #13
'{:x}'.format(11) #b
'{:#x}'.format(11) #0xb
'{:#X}'.format(11) #0XB
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值