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 done with N - (L % N)
, except for cases where L % N
is zero.
I have been using the following for now:
pad = (N - (L % N)) % N
This does not seem particularly legible, so sometimes I use
pad = N - (L % N)
if pad == N:
pad = 0
It seems overkill to use three lines of code for something so simple.
Alternatively, I can find the k
for which k * N >= L
, but using math.ceil
seems like overkill as well.
Is there a better alternative that I am missing? Perhaps a simple function somewhere?
The modulus of negative L will do it.
pad = -L % N
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With