将 int 格式设置为 000000_0000

Format int as 000000_0000

在 ironpython (Python 2.7) 中,我可以格式化一个 int 来输出这样的字符串:

1     --> 000000_0001
10000 --> 000001_0000

"{}".format 语法似乎不支持自定义字符。

这是我目前尝试的方法:

def format(self, num):
    pre = int(num * 0.0001)
    tail = int(num - (pre*1/0.0001))

    return "{}_{}".format("{0:06d}".format(pre), "{0:04d}".format(tail))

但我希望有更简洁的方法。在 C# 中应该是:

num.ToString("000000_0000")

编辑:我最终得到了 Parsa 的变体

def format(num):
    num = str(num).zfill(10)
    return "{}_{}".format(num[0:6], num[6:10])

怎么样:

total_length = 8
half_length = total_length / 2

num = 10000

zfilled_num = str(num).zfill(total_length)
underscored = zfilled_num[:half_length] + "_" + zfilled_num[half_length:]

print underscored
# 0001_0000

Try it online!

def print_with_format(i):
    print("{0}_{1}".format(str(i).zfill(8)[0:4], str(i).zfill(8)[4:8]))

print_with_format(18965)

按照 @Karl 的建议,先创建一个填充字符串,然后插入 _

方法如下:

def halve_it(n):
    p = '{:010d}'.format(n)
    return '{}_{}'.format(p[:6], p[6:])

print halve_it(12345)

输出:

>>> def halve_it(n):
...     p = '{:010d}'.format(n)
...     return '{}_{}'.format(p[:6], p[6:])
...
>>> print halve_it(10000)
000001_0000
>>> >>> print halve_it(12345)
000001_2345
>>> print halve_it(1)
000000_0001
>>> print halve_it(9876543)
000987_6543