You can use the zfill() method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
Answer from unbeknown on Stack OverflowI'm currently learning Python through Harvard's free CS50 course, and while working on the Outdated assignment, I noticed something very bizarre in this specific part below:
while True:
try:
date = input("Date: ")
if date.find("/"):
m, d, y = date.split("/")
print(f"{y}-{m:02}-{d:02}")
except EOFError:
print("")
break
The leading zeros in the identifiers inside the print function result with zeros being in the end, as opposed to the left. For instance, if m is 4, in this case, m will result in 40, instead of 04. In another part of the script using a similar method, this does not occur. Is there something I'm doing wrong? Sorry if its a stupid question, I'm still learning.
How to pad a string with leading zeros in Python 3 - Stack Overflow
f-strings in Python 3.6 are awesome
Strange behavior: leading zeros in formatted print function are reversed
Suppress leading zeroes in date time formatting?
You can use the zfill() method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
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
Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it's valid for both Python 2.x and Python 3.x.
It important to note that Python 2 is no longer supported.
Sample usage:
print(str(1).zfill(3))
# Expected output: 001
Description:
When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.
Syntax:
str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.
Since python 3.6 you can use f-string :
>>> length = "1"
>>> print(f'length = {length:03}')
length = 100
>>> print(f'length = {length:>03}')
length = 001