将整数格式化为带前导零的字符串的最佳方法? [英] Best way to format integer as string with leading zeros?

查看:40
本文介绍了将整数格式化为带前导零的字符串的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将前导零添加到整数以生成具有定义数量的数字 ($cnt) 的字符串.将这个简单的函数从 PHP 转换为 Python 的最佳方法是什么:

I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python:

function add_nulls($int, $cnt=2) {
    $int = intval($int);
    for($i=0; $i<($cnt-strlen($int)); $i++)
        $nulls .= '0';
    return $nulls.$int;
}

有没有可以做到这一点的函数?

Is there a function that can do this?

推荐答案

您可以使用 zfill() 方法用零填充字符串:

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

这篇关于将整数格式化为带前导零的字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆