Reputation: 6116
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?
Upvotes: 2
Views: 82
Reputation: 44878
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, ' ')
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.
Upvotes: 3
Reputation: 52151
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(",", "_")
Upvotes: 2