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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use the zfill() method to pad a string with zeros:
In [3]: str(1).zfill(2) Out[3]: '01'
Method 2
The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.
To output a string of length 5:
… in Python 3.5 and above: f-strings.
i = random.randint(0, 99999)
print(f'{i:05d}')
Search for f-strings here for more details.
… Python 2.6 and above:
print '{0:05d}'.format(i)
… before Python 2.6:
print "%05d" % i
See: https://docs.python.org/3/library/string.html
Method 3
Python 3.6 f-strings allows us to add leading zeros easily:
number = 5
print(f' now we have leading zeros in {number:02d}')
Have a look at this good post about this feature.
Method 4
You most likely just need to format your integer:
'%0*d' % (fill, your_int)
For example,
>>> '%0*d' % (3, 4) '004'
Method 5
Python 2.6 allows this:
add_nulls = lambda number, zero_count : "{0:0{1}d}".format(number, zero_count)
>>>add_nulls(2,3)
'002'
Method 6
For Python 3 and beyond:
str.zfill() is still the most readable option
But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 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
Method 7
You have at least two options:
- str.zfill:
lambda n, cnt=2: str(n).zfill(cnt) %formatting:lambda n, cnt=2: "%0*d" % (cnt, n)
If on Python >2.5, see a third option in clorz’s answer.
Method 8
One-liner alternative to the built-in zfill.
This function takes x and converts it to a string, and adds zeros in the beginning only and only if the length is too short:
def zfill_alternative(x,len=4): return ( (('0'*len)+str(x))[-l:] if len(str(x))<len else str(x) )
To sum it up – build-in: zfill is good enough, but if someone is curious on how to implement this by hand, here is one more example.
Method 9
A straightforward conversion would be (again with a function):
def add_nulls2(int, cnt):
nulls = str(int)
for i in range(cnt - len(str(int))):
nulls = '0' + nulls
return nulls
Method 10
This is my Python function:
def add_nulls(num, cnt=2): cnt = cnt - len(str(num)) nulls = '0' * cnt return '%s%s' % (nulls, num)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0