Simple Way To Calculate Padding Based On Modulo/remainder
If I have a string of length L=77 that I want to pad to a length that is a multiple of N=10. I am interested in computing just the amount of padding required. This can be easily do
Solution 1:
The modulus of negative L will do it.
pad = -L % N
Solution 2:
Isn't this one enough?
pad = (N - L) % N
Solution 3:
With math.ceil
:
from math import ceil
def pad(l, n):
return n*ceil(l/n) - l
assertpad(59, 10) == 1assertpad(60, 10) == 0assertpad(61, 10) == 9
Solution 4:
I mean couldn't you simply do
pad = N-L if N-L > 0 else 0
Solution 5:
Use the tenary conditional operator:
0 if (L % N) == 0 else N - (L % N)
Post a Comment for "Simple Way To Calculate Padding Based On Modulo/remainder"