3

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?

Mad Physicist
  • 76,709
  • 19
  • 122
  • 186

5 Answers5

4

The modulus of negative L will do it.

pad = -L % N
Bert Kellerman
  • 1,403
  • 9
  • 16
2

Isn't this one enough?

pad = (N - L) % N
Austin
  • 24,608
  • 4
  • 20
  • 43
1

With math.ceil:

from math import ceil

def pad(l, n):
    return n*ceil(l/n) - l

assert pad(59, 10) == 1
assert pad(60, 10) == 0
assert pad(61, 10) == 9
Thierry Lathuille
  • 21,301
  • 10
  • 35
  • 37
0

I mean couldn't you simply do

pad = N-L if N-L > 0 else 0
Grant Williams
  • 1,379
  • 10
  • 22
  • Sorry, but my question was unclear. I updated it. I wanted to find the padding for cases where the final length needs to be some arbitrary multiple of `N`, where I don't know the multiple. Unfortunately, I've basically invalidated your answer. My apologies. – Mad Physicist Apr 18 '18 at 15:25
  • Also, I object to computing the difference twice for cases where it is nonzero, which reduces this solution to using the `if` statement that makes me unhappy. – Mad Physicist Apr 18 '18 at 15:28
  • fair enough. You could have also used `pad = max(N-L, 0)` if you wanted. Although i cant imagine an extra subtraction is going to matter all that much – Grant Williams Apr 18 '18 at 15:39
0

Use the tenary conditional operator:

0 if (L % N) == 0 else N - (L % N) 
naroslife
  • 15
  • 2