如何格式化最多 N 位小数的数字,其中 N 是随机的



我想加密一个最多N位小数的数字。我使用的过程有时会生成的小数比N少,所以我需要在左边用零填充其余部分。我试过这个:

N = 5 # The number of decimals needed for encryption
encrypted = '%0Nd' % (x) # here x is a number used to encrypte the original number 

Nencrypted应该是一个先验确定的数字。

encrypted = '{:0{width}d}'.format(x, width=N)

带有格式字符串的Python 3.6解决方案:

encrypted = f'{d:0{N}}'

例如

>>> d = 5
>>> N = 3
>>> f'{d:0{width}}'
005

相关内容

最新更新