生成量身定制的千位定界符

Generate tailor made thousand delimiter

我想在Python中定制一千个分隔符。我正在生成 HTML 并想使用   作为千位分隔符。 (看起来像:1 000 000)

到目前为止,我找到了以下添加 , 作为分隔符的方法:

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

但我看不出能够使用类似的构造来获得另一个定界符。 '{0:|}'.format(1000000) 例如不起作用。有没有一种简单的方法可以将任何东西( )用作千位分隔符?

嗯,你总是可以这样做:

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

结果:'1|000|000'


这是一个简单的算法。它的前一个版本(ThSep 两次修订)没有处理像  :

这样的长分隔符
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))

ThSep(1000000, '&thinsp;')ThSep(1000000, '|')调用它以获得你想要的结果。

虽然它比第一种方法慢 4 倍,所以您可以尝试将其重写为生产代码的 C 扩展。仅当速度非常重要时才如此。我在半分钟内转换了 2 000 000 个负数和正数以进行测试。

没有内置方法可以做到这一点,但您可以使用 str.replace,如果该数字是唯一的当前值

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

这个在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(",", "_")