I have a paper where the editors request I remove thousands separators (comma) for four digit-numbers. I used f-strings:
form=",.0f"
format(123456, form)
> '123,456'
format(1234, form)
> '1,234'
I cannot find the correct format to keep '123,456'
but remove the comma for '1234'
.
The python docs do not provide an answer. I could provide a custom formatting function, but I would like to avoid this.
2
There’s no built-in way to do this, but it isn’t hard to do by hand:
s = format(num, '.0f')
if len(s) <= 4:
return s
return format(num, ',.0f')
1
I would have preferred fixing this with f-strings, but it is not possible. Therefore, I followed @nneonneo’s answer. Here’s the complete method, for integration into matplotlib (following their docs):
import matplotlib.ticker as ticker
@ticker.FuncFormatter
def major_formatter(x, pos):
s = format(x, '.0f')
if len(s) <= 4:
return s
return format(x, ',.0f')
...
ax.yaxis.set_major_formatter(major_formatter)