Home > Software engineering >  How to pad a zero input in an argparser default?
How to pad a zero input in an argparser default?

Time:06-03

today = datetime.datetime.now()
day_before_date1 = datetime.date.today()-datetime.timedelta(days=2)
day_before_date = day_before_date1.strftime("%d")
print(day_before_date)  # 01 (is the output)

I have to use arg parser in python to take input for day. If I don't give any input it defaults to presentdate-2, which is 01.

parser.add_argument('number',type=int, help="Number represents date" , nargs='?' , default=day_before_date , const="num")

I have set default=int(day_before_date) but it still registers the input as 1 and not 01 when I print(args.number) I need 01 when i print(args.number).

CodePudding user response:

You can use the str.rjust method, this will guarantee that you will only ever have 2 characters so if it is 11 it will output '11' but if it is 3 it will output '03'

>>> a = 1
>>> str(a).rjust(2,"0")
"01"

another method is to use inline formating with f-strings.

>>> a = 1
>>> b = f"{a:02d}"
>>> b
"01"

Or you can use conditional statement (not recommended).

>>> a = 1
>>> b = '0'   str(a) if len(str(a)) == 1 else str(a)
>>> b
'01'

CodePudding user response:

You have two options. The first is to change what type your argument is in argparser:

parser.add_argument('number',type=str, help="Number represents date" , nargs='?' , default="01", const="num")
...
day_number_arg = int(args.number)
... # use `day_number_arg` wherever you would have used `args.number`
print(args.number)  # will print '01' if the default is used.

Here you take in a string and convert it to a number. You can print out the original argument as the string passed in, or the default.

Elsewise you can take your calculated value and use a format string:

day_number = 1
f"{day_number:02d}"

This says 'print two digits of day_number'. In this manner you can format the output, meaning you can use whatever your final value is. In general this would be the recommend method.

  • Related