[Tutor] rounding up to the nearest multiple of 8

eryksun eryksun at gmail.com
Fri Oct 5 10:31:08 CEST 2012


On Fri, Oct 5, 2012 at 2:54 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> 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    '

Or use floor division with -n:

    >>> lenstep = lambda s, n: -n * (len(s) // -n)

    >>> mystring = '123412341234'
    >>> "{1:<{0}s}".format(lenstep(mystring, 8), mystring)
    '123412341234    '
    >>> "{1:>{0}s}".format(lenstep(mystring, 8), mystring)
    '    123412341234'
    >>> "{1:^{0}s}".format(lenstep(mystring, 8), mystring)
    '  123412341234  '


More information about the Tutor mailing list