ram*_*sus 270 python string-formatting
我需要将前导零添加到整数以生成具有已定义数字位数的字符串($ cnt).将这个简单函数从PHP转换为Python的最佳方法是什么:
function add_nulls($int, $cnt=2) {
$int = intval($int);
for($i=0; $i<($cnt-strlen($int)); $i++)
$nulls .= '0';
return $nulls.$int;
}
Run Code Online (Sandbox Code Playgroud)
有没有可以做到这一点的功能?
小智 569
您可以使用该zfill()方法用零填充字符串:
In [3]: str(1).zfill(2)
Out[3]: '01'
Run Code Online (Sandbox Code Playgroud)
use*_*450 156
标准方法是使用格式字符串修饰符.这些格式字符串方法在大多数编程语言中都可用(例如通过c中的sprintf函数),并且是一个方便的工具.
i = random.randint(0,99999)
print "%05d" % i
Run Code Online (Sandbox Code Playgroud)
这将输出一个长度为5的字符串.
编辑:在Python2.6及更高版本中,还有:
print '{0:05d}'.format(i)
Run Code Online (Sandbox Code Playgroud)
请参阅:https://docs.python.org/2/library/string.html
Sil*_*ost 67
您很可能只需要格式化整数:
'%0*d' % (fill, your_int)
Run Code Online (Sandbox Code Playgroud)
例如,
>>> '%0*d' % (3, 4)
'004'
Run Code Online (Sandbox Code Playgroud)
Ser*_*ujo 55
Python 3.6 f-strings允许我们轻松添加前导零:
number = 5
print(f' now we have leading zeros in {number:02d}')
Run Code Online (Sandbox Code Playgroud)
看看这篇好帖子.
clo*_*orz 21
Python 2.6允许这样:
add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count)
>>>add_nulls(2,3)
'002'
Run Code Online (Sandbox Code Playgroud)
Yun*_*age 15
对于Python 3及更高版本:str.zfill()仍然是最易读的选项
但是查看新的强大的str.format()是一个好主意,如果你想填充不是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
Run Code Online (Sandbox Code Playgroud)
您至少有两个选择:
lambda n, cnt=2: str(n).zfill(cnt)% 格式: lambda n, cnt=2: "%0*d" % (cnt, n)如果在Python> 2.5上,请参阅clorz答案中的第三个选项.