Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何设置N为随机数的N位小数的格式_Python_Python 3.x_Formatting - Fatal编程技术网

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

两个答案都很完美,我认为乔纳斯第一行的方法要优雅得多。