On Thu, Oct 4, 2012 at 4:04 PM, Joel Goldstick <joel.goldst...@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' _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor