How would you add zeros to the beginning of an Integer, such that there are 4 total digits in the number?

Without using zfill or format or any other obscure functions.

example:

turn 15 into 0015

or 234 into 0234

4 comments · 75% upvoted · other discussions

comments

socal_nerdtastic

zfill or format are not obscure at all.

A python integer cannot have leading zeros. It's simply not possible. zfill and format work with strings. You can also use f-strings to add zeros to a string:

data = 15
print(f"{data:0>4}")

That said this sounds like an XY problem. We could help a lot more if you told us what problem you are trying to solve, not just how you are trying to solve it. What's the big picture here? http://xyproblem.info

thattiguy

This can work:

f=lambda n: '0'*(4-len(str(n)))+str(n)

f(15)='0015'

Basically, just convert to string, find the length, and use that to calculate the number of zeros required. Then use '0'*n to generate that number of zeroes and slap the original number on the end.

socal_nerdtastic

How about

f=lambda n:f(x) if len(x:=f'0{n}')<4 else x
Empik002

you would have to probably do: else str(x) Because there would either be a string or int as a return of the function (if you give actuall int to the function ofc) and that could cause some prblems.

EDIT: wait why is it recursive? EDIT2: oh right i am just stupid