简体   繁体   English

使用 % 运算符填充位数

[英]Use number of digits to pad with `%` operator

Consider the code:考虑代码:

>>> value = 5
>>> '%02d'%value
'05'

Now instead of hardcoing number of padding digits (in this case 2 ) I want to use another variable for that:现在,我想使用另一个变量来代替硬编码的填充数字(在本例中为2 ):

>>> pad = 3

So that now I can get equivalent of:所以现在我可以得到相当于:

>>> '%03d'%value
'005'

I could convert to str and use zfill but looking for a more elegant solution.我可以转换为str并使用zfill但寻找更优雅的解决方案。

What version of Python are you using?您使用的是哪个版本的 Python? In modern versions (3.6+) it is very easy to implement using f-strings:在现代版本(3.6+)中,使用 f-strings 很容易实现:

f'{value:0{pad}}'

In earlier versions, you still can use str.format :在早期版本中,您仍然可以使用str.format

'{0:0{1}}'.format(value, pad)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM