Search code examples
pythonformatting

f-strings: Skip thousands delimiter (comma) for four digits (1000); limit comma to five or more digits


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.


Solution

  • 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')