Skip to content Skip to sidebar Skip to footer

Python Argparse: Does It Have To Return A List?

I am trying to obtain a string of numbers from argparse. It's optional whether or not the argument -n is provided. import argparse parser = argparse.ArgumentParser() parser.add_ar

Solution 1:

Do not try to concatenate None and "hi ":

print("hi", test)

or

print("hi " + (test or ''))

or test if test is set to None explicitly:

iftest is not None:
    print("hi", test)

Solution 2:

Solution 3:

Regarding the question from the title, when nargs is used, the returned value of args.n is a list (even if the nargs=1 is used). So when only 1 argument is expected, you may decide to not use nargs at all to avoid returning a list.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-n')
args = parser.parse_args()
test = args.n
if test:
    print("hi " + test) 

Post a Comment for "Python Argparse: Does It Have To Return A List?"