I\'m currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1]
represents. Is it simpl
Adding a few more points to Jason's Answer :
For taking all user provided arguments : user_args = sys.argv[1:]
Consider the sys.argv as a list of strings as (mentioned by Jason). So all the list manipulations will apply here. This is called "List Slicing". For more info visit here.
The syntax is like this : list[start:end:step]. If you omit start, it will default to 0, and if you omit end, it will default to length of list.
Suppose you only want to take all the arguments after 3rd argument, then :
user_args = sys.argv[3:]
Suppose you only want the first two arguments, then :
user_args = sys.argv[0:2] or user_args = sys.argv[:2]
Suppose you want arguments 2 to 4 :
user_args = sys.argv[2:4]
Suppose you want the last argument (last argument is always -1, so what is happening here is we start the count from back. So start is last, no end, no step) :
user_args = sys.argv[-1]
Suppose you want the second last argument :
user_args = sys.argv[-2]
Suppose you want the last two arguments :
user_args = sys.argv[-2:]
Suppose you want the last two arguments. Here, start is -2, that is second last item and then to the end (denoted by ":") :
user_args = sys.argv[-2:]
Suppose you want the everything except last two arguments. Here, start is 0 (by default), and end is second last item :
user_args = sys.argv[:-2]
Suppose you want the arguments in reverse order :
user_args = sys.argv[::-1]
Hope this helps.