如果我有一个长度为L = 77的字符串,我希望将其填充为N = 10的倍数的长度.我对仅计算所需的填充量感兴趣.使用N - (L % N)可以很容易地做到这一点,除了L % N为零的情况.
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对于这么简单的事情,使用三行代码似乎是矫kill过正.
It seems overkill to use three lines of code for something so simple.
或者,我可以找到k * N >= L的k,但是使用math.ceil似乎也过分了.
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?
推荐答案负L的模量可以做到这一点.
The modulus of negative L will do it.
pad = -L % N更多推荐
基于模数/余数计算填充的简单方法
发布评论