Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 614
Mad Physicist Avatar asked Mar 07 '23 09:03

Mad Physicist


1 Answers

The modulus of negative L will do it.

pad = -L % N
like image 121
Bert Kellerman Avatar answered Mar 20 '23 10:03

Bert Kellerman