user4411105
user4411105

Reputation:

How to format a number up to N decimals where N is random

I want to encrypt a number up to N decimals. The process I use sometimes generates less decimals than N so I need to pad the rest with zeroes to the left. I tried this:

N = 5 # The number of decimals needed for encryption

encrypted = '%0Nd' % (x) # here x is a number used to encrypte the original number 

but N in encrypted should be a number priory determined.

Upvotes: 1

Views: 68

Answers (2)

Jonas Adler
Jonas Adler

Reputation: 10799

Python 3.6 solution with format strings:

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

For example,

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

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

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

Upvotes: 1

Related Questions