最好的方式来格式的整数作为串导致零?[重复]
-
06-09-2019 - |
题
这个问题已经有一个答案在这里:
- 显示数领先的零 17的答案
我需要增加导致零为整以使一串的定义数量的数字($cnt)。什么是最好的方式把这种简单的功能,从PHP蟒蛇:
function add_nulls($int, $cnt=2) {
$int = intval($int);
for($i=0; $i<($cnt-strlen($int)); $i++)
$nulls .= '0';
return $nulls.$int;
}
是否有一个功能,可以做到这一点?
解决方案
你可以使用 zfill()
法垫串零:
In [3]: str(1).zfill(2)
Out[3]: '01'
其他提示
标准的方法是使用的格式串改性剂。这些格式串的方法都可以在最编程语言(通过的sprintf功能在c),并是一个方便的工具知道。
i = random.randint(0,99999)
print "%05d" % i
这将输出的一个字符串的长度5.
编辑:在Python2.6及以上,还有:
print '{0:05d}'.format(i)
你很可能只需要你的格式整数:
'%0*d' % (fill, your_int)
例如,
>>> '%0*d' % (3, 4)
'004'
蟒蛇3.6f-串允许我们可以添加导致零容易:
number = 5
print(f' now we have leading zeros in {number:02d}')
看看 这种良好的职位 关于这一特征。
蟒蛇2.6允许这样的:
add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count)
>>>add_nulls(2,3)
'002'
Python3及以后:str.zfill()仍然是最可读的选择
但它是一个很好的想法寻找到新的和强大的海峡。格式(),什么如果你想要垫上东西是不是0?
# if we want to pad 22 with zeros in front, to be 5 digits in length:
str_output = '{:0>5}'.format(22)
print(str_output)
# >>> 00022
# {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5
# another example for comparision
str_output = '{:#<4}'.format(11)
print(str_output)
# >>> 11##
# to put it in a less hard-coded format:
int_inputArg = 22
int_desiredLength = 5
str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
print(str_output)
# >>> 00022
你至少有两个选择:
- str.zfill:
lambda n, cnt=2: str(n).zfill(cnt)
%
格式化:lambda n, cnt=2: "%0*d" % (cnt, n)
如果在Python>2.5,请参阅第三个选择在clorz的答复。
一个班轮替代的内在 zfill
.
这个函数 x
并将其转换为一串,并增加了零开始仅仅如果长度太短:
def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )
总的来说-建立: zfill
足够好,但是,如果有人奇怪的是有关如何实施这一方面,这是一个例子。
一个简单的转换将是(再次用功能):
def add_nulls2(int, cnt):
nulls = str(int)
for i in range(cnt - len(str(int))):
nulls = '0' + nulls
return nulls
这是我的蟒蛇功能:
def add_nulls(num, cnt=2):
cnt = cnt - len(str(num))
nulls = '0' * cnt
return '%s%s' % (nulls, num)
不隶属于 StackOverflow