-4

if given a command like:

python 1.py ab 2 34

How to print the next argument while you are currently sitting on the one before. e.g if x is ab then I want to print 2:

import sys
for x in sys.argv[1:]:
    print next element after x
33ted
  • 689
  • 1
  • 5
  • 14
  • 1
    use `enumerate` to keep track of your current loop index; that should help. –  Mar 23 '16 at 05:44
  • 3
    Doing argument parsing? Please consider `argparse`. You will save a lot of sanity. It gives you useful help messages, robust argument parsing, and is pretty easy to use too. – nneonneo Mar 23 '16 at 05:45
  • If you want more help, you should provide more details about your use case. For example, one thing that is not clear, after reading ab, and so printing 2, do you need to read 2 and so printing 34? Also, if you provide why you want to do this (e.g., parsing the command line arguments for setting options), there are some packages out there already implementing what you want to do. – albertoql Mar 23 '16 at 06:32
  • yes i want to read 2 and print 34. i want to do this cause i have a string that consists of name of angle followed by angle value, then name of another angle followed by rotation value and so on. i'm not allowed to use Regex. e.g python 1.py a 3.1 b 4 (a is angle and 3.1 value of it, b is another angle and 4 is how much we want to rotate it) – 33ted Mar 23 '16 at 06:40

1 Answers1

1

I am unsure what you want to print but this syntactic sugar can help:

for x in sys.argv[1::2]:
    print x

This prints every other element. So this will return ab 34

for x in sys.argv[2::2]:
    print x

This will return 2

The number after the :: is how many slots in the array.

Edit: To answer your specific question:

val = 1
for index, x in enumerate(sys.argv[1::2]):
    val += 1
    print sys.argv[index+val]

The index increases by 1 each time, and the val by 1 too, meaning every loop we skip 2 variables. Hence for something like python yourcode.py a 1 b 2 c 3 d 4 output will be 1 2 3 4

Olegp
  • 182
  • 2
  • 14