[Tutor] rounding up to the nearest multiple of 8

Albert-Jan Roskam fomcl at yahoo.com
Fri Oct 5 10:24:11 CEST 2012

```----- Original Message -----

> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Cc:
> Sent: Friday, October 5, 2012 8:54 AM
> Subject: Re: [Tutor] rounding up to the nearest multiple of 8
>
> On Thu, Oct 04, 2012 at 05:26:13PM -0400, eryksun wrote:
>>  On Thu, Oct 4, 2012 at 4:04 PM, Joel Goldstick
> <joel.goldstick at gmail.com> wrote:
>>  >
>>  >>>> my_string = "123"
>>  >>>> pad = 8 - len(my_string) % 8
>>  >>>> my_string = my_string + " " * pad
>>  >>>> my_string
>>  > '123     '
>>
>>  If len(my_string) is already a multiple of 8, the above sets pad to 8:
>>
>>      >>> s = "12345678"
>>      >>> pad = 8 - len(my_string) % 8
>>      8
>
> Here's another way:
>
>
> py> from __future__ import division
> py> from math import ceil
> py> "%*s" % (int(ceil(len(mystring)/8)*8), mystring)
> '    123412341234'
>
>
> Or left-justified:
>
> py> "%-*s" % (int(ceil(len(mystring)/8)*8), mystring)
> '123412341234    '
>
>
> In Python 3, there is no need for the "from __future__" line.

Hi Steven, Eryksun, Joel,

Thanks for your replies! Steven, I noticed that the "from __future__" line can be omitted if len(mystring) is divided by 8.0 (ie, by a float rather than an int). I compared the "ceil" approach to the "modulo" approach, and found that the ceil approach is 2.6 times slower than the other approach. In this case, that's a relevant difference as the padding sometimes needs to be done millions of times.

import timeit
ver1 = timeit.timeit("""
import math
value = "1234"
value = "%-*s" % (int(math.ceil(len(value)/8.0)*8), value)
""")
ver2 = timeit.timeit("""
value = "1234"
value = value.ljust( len(value) + (-len(value) % 8) )
""")

print ver1
print ver2
print ver1 / ver2

```