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

  • 16
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python 中,字符串占位符是一种用于格式化字符串的特殊语法。以下是 Python 中常用的字符串占位符: - `%s`:用于字符串格式化,表示用字符串替换占位符。 - `%d`:用于整数格式化,表示用整数替换占位符。 - `%f`:用于浮点数格式化,表示用浮点数替换占位符。 - `%x`:用于十六进制格式化,表示用十六进制数替换占位符。 例如,以下代码将使用字符串占位符格式化一个字符串: ```python name = 'John' age = 25 height = 1.75 # 使用字符串占位符格式化字符串 msg = "My name is %s, I'm %d years old, and I'm %.2f meters tall." % (name, age, height) print(msg) ``` 输出结果为: ``` My name is John, I'm 25 years old, and I'm 1.75 meters tall. ``` 除了使用 `%` 运算符外,还可以使用 `format()` 方法进行字符串格式化。例如: ```python name = 'John' age = 25 height = 1.75 # 使用 format() 方法格式化字符串 msg = "My name is {}, I'm {} years old, and I'm {:.2f} meters tall.".format(name, age, height) print(msg) ``` 输出结果与上例相同: ``` My name is John, I'm 25 years old, and I'm 1.75 meters tall. ``` 需要注意的是,Python 3.6 及以后版本还引入了 f-string 语法,可以更方便地进行字符串格式化。例如: ```python name = 'John' age = 25 height = 1.75 # 使用 f-string 格式化字符串 msg = f"My name is {name}, I'm {age} years old, and I'm {height:.2f} meters tall." print(msg) ``` 输出结果也与上例相同: ``` My name is John, I'm 25 years old, and I'm 1.75 meters tall. ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值