2

I want to tailor-make a thousand delimiter in Python. I am generating HTML and want to use   as thousand separator. (It would look like: 1 000 000)

So far I have found the following way to add a , as a separator:

>>> '{0:,}'.format(1000000)
'1,000,000'

But I don't see to be able to use a similar construction to get another delimiter. '{0:|}'.format(1000000) for example does not work. Is there an easy way to use anything (i.e.,  ) as a thousand separator?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
jonalv
  • 5,706
  • 9
  • 45
  • 64

2 Answers2

3

Well, you can always do this:

'{0:,}'.format(1000000).replace(',', '|')

Result: '1|000|000'


Here's a simple algorithm for the same. The previous version of it (ThSep two revisions back) didn't handle long separators like  :

def ThSep(num, sep = ','):
    num = int(num)

    if not num:
        return '0'

    ret = ''
    dig = 0
    neg = False

    if num < 0:
        num = -num
        neg = True

    while num != 0:
        dig += 1
        ret += str(num % 10)
        if (dig == 3) and (num / 10):
            for ch in reversed(sep):
                ret += ch
            dig = 0

        num /= 10

    if neg:
        ret += '-'

    return ''.join(reversed(ret))

Call it with ThSep(1000000, '&thinsp;') or ThSep(1000000, '|') to get the result you want.

It's about 4 times slower than the first method, though, so you can try rewriting this as a C extension for production code. This is only if speed matters much. I converted 2 000 000 negative and positive numbers in half a minute for the test.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • @BhargavRao, nothing. In the previous revision, __`ThSep`__ couldn't handle them, not the version with `replace` – ForceBru Apr 27 '16 at 14:19
  • 1
    Thanks for that. However, PEP 378 already mentions that replace is the correct way. So I guess it is a bit of reinventing the wheel! Anyway, tis not wrong at all. Good answer. Cheers – Bhargav Rao Apr 27 '16 at 14:24
2

There is no built in way to do this, But you can use str.replace, if the number is the only present value

>>> '{0:,}'.format(1000000).replace(',','|')
'1|000|000'

This is mentioned in PEP 378

The proposal works well with floats, ints, and decimals. It also allows easy substitution for other separators. For example:

format(n, "6,d").replace(",", "_")
Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140