I've been searching for a simpler way to do this, but i'm not sure what search parameters to use. I have a floating point number, that i would like to round, convert to a string, then specify a custom format on the string. I've read through the .format docs, but can't see if it's possible to do this using normal string formatting.
The output i want is just a normal string, with spaces every three chars, except for the last ones, which should have a space four chars before the end.
For example, i made this convoluted function that does what i want in an inefficient way:
def my_formatter(value): final = [] # round float and convert to list of strings of individual chars c = [i for i in '{:.0f}'.format(value)] if len(c) > 3: final.append(''.join(c[-4:])) c = c[:-4] else: return ''.join(c) for i in range(0, len(c) // 3 + 1, 1): if len(c) > 2: final.insert(0, ''.join(c[-3:])) c = c[:-3] elif len(c) > 0: final.insert(0, ''.join(c)) return(' '.join(final)) e.g.
>>> my_formatter(123456789.12) >>> '12 345 6789' >>> my_formatter(12345678912.34) >>> '1 234 567 8912' Would really appreciate guidance on doing this in a simpler / more efficient way.