python: 字符串占位符的“{0:2} 以及 {:02}“

看到这么奇怪的占位符,估计都是一脸懵逼。而且网上搜不到。

其实很简单,试一下就知道了。

print("{0:2}".format(10, 20, 30, 40))
# 10
#  1
print("{:2}: {}".format(1, 2, 3, 4))
#  1: 2

通过简单是打印就明白了:

  • {0:2}表示的是一个占位符
  • {0:2}表示至少占两个位,前面是一个空格。显示的效果为 x, 其中x是被打印的内容。
  • 为了方便,可以省略0,直接表示为{:2}

更实用的 格式化 {:02} ,最少显示2个字符长度,前面不够的部分全部补0, 超过的部分忽略不计。

# 当然这里肯定可以是 {0:3}, {0:4} 

    print("{:05}".format(11)) 			# 输出 00011
    print("{:02}".format(0))			# 输出 00
    print("{:02}".format(7))			# 输出 07
    print("{:02}".format(95)) 			# 输出 95
    print("{:02}".format(91225))		# 输出 91225

不过这里也不能乱写,比如 {:-5}, {:x3} 这样都会报错,只有补零这个是有效的。

输出:

00011
00
07
95
91225

比如现在是7点钟,但是可能希望显示的字符串是"07", 那么,这个字符串的格式化就非常方便了,不然还得自己去判断数字的大小,然后动态去补0.

Note When formatting a number (int, float, complex, decimal.Decimal and subclasses) with the n type (ex: ‘{:n}’.format(1234)), the function temporarily sets the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep fields of localeconv() if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads.

https://docs.python.org/3/library/stdtypes.html#str.format

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值