I am trying to output a longer integer in a more readable manner. How can I format it as a string with spaces after a certain number of digits?
For example, I would like 12345678 to be output as 1234 56 78
One option is use re module, match the number with regex and reformat it:
import re re.sub(r"(\d{4})(\d{2})(\d{2})", r"\1 \2 \3", "12345678") # '1234 56 78' Or for readability you might want to format it with a thousand separator:
"{:,d}".format(12345678) # '12,345,678' 1234567 will be but this return 1234567 instead of 1234 56 7.You can also do this using a combination of itertools and str.join():
>>> from itertools import zip_longest >>> >>> def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) >>> def pretty_print(start, number, delim=' '): number = str(number) end = delim.join(''.join(g) for g in grouper(number[start:], 2, '')) return number[:start] + delim + end >>> number = 12345678 >>> pretty_print(4, number, ' ') '1234 56 78' >>> pretty_print(4, number, ',') '1234,56,78' >>> pretty_print(4, number, '|') '1234|56|78' You could do something like this:
>>> from itertools import islice >>> def solve(num, n=4): ... s = str(num) ... fmt = [n] + [2] * ((len(s) - n) // 2); ... it = iter(s) ... return ' '.join(''.join(islice(it, x)) for x in fmt) >>> solve(12345678) '1234 56 78' >>> solve(1234567890) '1234 56 78 90' If the number is always going to be 8 digits, you need do nothing more complicated than use a simple string formatting spec:
>>> '{}{}{}{} {}{} {}{}'.format(*str(12345678)) 1234 56 78 If you could have, say, any even number of digits of length 2 or greater, and you want to have the first up-to 4 digits grouped, and then the following digit pairs grouped after that, you can still make this work pretty easily:
>>> digits8 = str(12345678) >>> ('{}{}' + ' '.join('{}{}' for _ in range(len(digits)//2-1))).format(*digits) 1234 56 78 >>> digits6 = str(123456) >>> ('{}{}' + ' '.join('{}{}' for _ in range(len(digits)//2-1))).format(*digits) 1234 56 >>> digits4 = str(1234) >>> ('{}{}' + ' '.join('{}{}' for _ in range(len(digits)//2-1))).format(*digits) 1234 >>> digits2 = str(12) >>> ('{}{}' + ' '.join('{}{}' for _ in range(len(digits)//2-1))).format(*digits) 12 As a function:
def special_format(number): digits = str(int(number)) if len(digits)%2 != 0: raise ValueError('Number must have an even number of digits.') return ('{}{}' + ' '.join('{}{}' for _ in range(len(digits)//2-1))).format(*digits) Now you can just do this:
>>> special_format(12345678) '1234 56 78' >>> special_format(123456) '1234 56' >>> special_format(12345678123456) '1234 56 78 12 34 56' >>> special_format(12) '12'
1234 56 78more readable than12345678?