问题
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?
回答1:
The modulus of negative L will do it.
pad = -L % N
回答2:
Isn't this one enough?
pad = (N - L) % N
回答3:
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
回答4:
I mean couldn't you simply do
pad = N-L if N-L > 0 else 0
回答5:
Use the tenary conditional operator:
0 if (L % N) == 0 else N - (L % N)
来源:https://stackoverflow.com/questions/49903319/simple-way-to-calculate-padding-based-on-modulo-remainder