I was looking for an easier way to do this, but I'm not sure which search options to use. I have a floating point number that I would like to round, convert to a string, and then specify a custom format in the string. I read the .format docs but can't see if it's possible to do this using normal string formatting.
The output I want is a regular line with spaces every three characters, with the exception of the last, which should have a space of four characters to the end.
For example, I made this collapsed function that does what I want is inefficient:
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)
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))
eg.
>>> my_formatter(123456789.12)
>>> '12 345 6789'
>>> my_formatter(12345678912.34)
>>> '1 234 567 8912'
It would be very helpful if you would do it in a simpler and more efficient way.