Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force argparse to return a list of strings?

i need to use argparse to accept a variable number of strings from command line, but when i pass zero arguments i get a string as result instead of a list of one string.

argparser = argparse.ArgumentParser()
argparser.add_argument(
    '--example',
    nargs='*',
    default='default_value',
    type=str)

args = argparser.parse_args()

for e in args.example:
    print(e)

When executing this python program --example first_arg second_arg i get the expected result:

first_arg
second_arg

Even with one argument everything is fine, but executing this python program i get:

d
e
f
a
u
l
t
_
v
a
l
u
e

I'd need to iterate over the list without considering how many elements it has, how could i solve this? Thank you in advance.

like image 950
Niccolò Galli Avatar asked Oct 29 '25 08:10

Niccolò Galli


2 Answers

Set the default to a list instead of a string:

argparser.add_argument(
    '--example',
    nargs='*',
    default=['default_value'],
    type=str)
like image 110
Code-Apprentice Avatar answered Oct 31 '25 00:10

Code-Apprentice


Your default value is a str which can be iterated in python, you can change the default to a list like this:

argparser.add_argument(
    '--example',
    nargs='*',
    default=['default_value'],
    type=str)
like image 31
Alex Avatar answered Oct 31 '25 01:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!