Python 如何设置N为随机数的N位小数的格式
我想加密一个不超过Python 如何设置N为随机数的N位小数的格式,python,python-3.x,formatting,Python,Python 3.x,Formatting,我想加密一个不超过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 但是加密的中的N应该是一个事先确定的数字。带格式字符串的Python 3.6解决方案: encrypted
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
但是
加密的中的N
应该是一个事先确定的数字。带格式字符串的Python 3.6解决方案:
encrypted = '{:0{width}d}'.format(x, width=N)
encrypted = f'{d:0{N}}'
比如说,
>>> d = 5
>>> N = 3
>>> f'{d:0{width}}'
005
两个答案都很完美,我认为乔纳斯第一行的方法要优雅得多。