[Tutor] rounding up to the nearest multiple of 8
Steven D'Aprano
steve at pearwood.info
Fri Oct 5 08:54:59 CEST 2012
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
> >>> pad
> 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.
--
Steven
More information about the Tutor
mailing list