On Thu, Oct 4, 2012 at 3:47 PM, Albert-Jan Roskam <fo...@yahoo.com> wrote: > Hi, > > The function below works, but it's such a kludge! Is there a way to make this > more elegant? > As said in the docstring, I want to round up a given integer to the nearest > multiple of 8. I was thinking > of something like math.ceil. > > def _getPadding(charlen): > """ Helper function to replace null bytes ('\x00') at the end of > string values. Rounds up <charlen> to the nearest multiple of 8. > Every string value is 8 bytes or a multiple thereof. For example, a > 5-character string needs a padding of 3 spaces to prevent the > null bytes > >>> dict([(charlen, _getPadding(charlen)) for charlen in range(1, 40, 7)]) > {1: 8, 36: 40, 8: 8, 15: 16, 22: 24, 29: 32} > >>> s = "I love Python" > >>> s.ljust(_getPadding(len(s))) > 'I love Python ' > """ > i = 0 > while True: > i += 1 > if (i * 8) > charlen: > return (i * 8) % charlen + charlen if charlen > 1 else 8 > if __name__ == "__main__": > import doctest > doctest.testmod() > > Thanks! > > Regards, > Albert-Jan > > >>> my_string = "123" >>> pad = 8 - len(my_string) % 8 >>> my_string = my_string + " " * pad >>> my_string '123 '
-- Joel Goldstick _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor