Python custom getopt -


hello i'm new python programming , wasn't sure how use getopt. so, since thought python pretty straight forward language, decided write own getopt function. goes this:

string = "a b -c -d" list = string.split()  def get_short_opts(args):    opts = ""    word in args:       print("word = " + word)       if word[0] == '-' , word[1] != '-':          opts += word[1:]   #to remove '-'          args.remove(word)     print("opts = " + opts)    print("args = " + str(args))     return opts  print(get_short_opts(list)) 

basically, function returns characters located after "-" character. works when use multiple options @ 1 time , 1 "-" , if

["-a", "arg", "-b"]  

but when try pass multiple options after each other, doesn't work. main code above example of when not work. explain why works , not other times? appreciated. thank you!

problem

the problem can't delete list while you're iterating through it.

see this question, this answer quoting the official python tutorial:

if need modify sequence iterating on while inside loop (for example duplicate selected items), recommended first make copy. iterating on sequence not implicitly make copy.

(c++ people call "iterator invalidation," don't know pythonic term it, if there one.)

solution

iterate on copy of args , remove original:

string = "a b -c -d" list = string.split()  def get_short_opts(args):    opts = []    word in args[:]:       print("word = " + word)       if word[0] == '-' , word[1] != '-':          opts.append(word[1:])   #to remove '-'          args.remove(word)     print("opts = " + str(opts))    print("args = " + str(args))     return opts  print(get_short_opts(list)) 

the args[:] notation slice beginning end of args, in other words, whole thing. slice copy, , not original. can remove original args did before, without affecting iteration sequence.

also notice have changed opts string list. seemed make sense way. can iterate through it, count members, etc. can put way had (a string each option concatenated) if want.


Comments