[Tutor] rounding up to the nearest multiple of 8

eryksun eryksun at gmail.com
Thu Oct 4 23:26:13 CEST 2012


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
    >>> pad
    8

You could special case when the modulo value is 0, or use pad % 8, but
I think it's simpler to calculate "-len(s) % 8":

    >>> [(charlen, -charlen % 8) for charlen in range(9)]
    [(0, 0), (1, 7), (2, 6), (3, 5), (4, 4), (5, 3), (6, 2), (7, 1), (8, 0)]


For example:

    >>> len_mod = lambda s, n: len(s) + (-len(s) % n)

    >>> s = ''; s.ljust(len_mod(s, 8))
    ''
    >>> s = '12345678'; s.ljust(len_mod(s, 8))
    '12345678'
    >>> s = '123456'; s.ljust(len_mod(s, 8))
    '123456  '
    >>> s = '123456789'
    >>> len_mod(s, 8)
    16
    >>> s.ljust(len_mod(s, 8))
    '123456789       '

    >>> s.ljust(len_mod(s, 9))
    '123456789'


More information about the Tutor mailing list