5

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?

8
  • Isn't it enough to use N - L? Commented Apr 18, 2018 at 15:18
  • @MegaIng. Sorry, was unclear. Updated the question. Commented Apr 18, 2018 at 15:23
  • Why don't use string formatting options for this? Commented Apr 18, 2018 at 15:23
  • @alec_djinn. Because the fact that we are talking about strings is irrelevant. For that matter, what string formatting options? Commented Apr 18, 2018 at 15:24
  • @MadPhysicist Thanks for the clarification. Check stackoverflow.com/questions/20309255/… for padding solutions using string formatting Commented Apr 18, 2018 at 15:25

5 Answers 5

5

The modulus of negative L will do it.

pad = -L % N 
Sign up to request clarification or add additional context in comments.

Comments

2

Isn't this one enough?

pad = (N - L) % N 

1 Comment

That actually reduces to the accepted answer. Clever.
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 

1 Comment

That does not seem any simpler than taking the modulo twice, but may be easier to understand.
0

I mean couldn't you simply do

pad = N-L if N-L > 0 else 0 

3 Comments

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.
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.
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
0

Use the tenary conditional operator:

0 if (L % N) == 0 else N - (L % N) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.