0

The code

def main(bar):
    bar = str(bar)
    print bar
main(sys.argv[1:])

prints

['bar']

, instead of just

bar

. What should I do to make the input argument exactly string? Thanks. (Python 2.5.2)

BeTheSame
  • 13
  • 1

3 Answers3

6

By passing sys.argv[1:] you're passing a range of the first argument as well as every following argument. You can do any of the following independently to get the desired results

# Target the 1 element when passing in
main(sys.argv[1])

# or this inside of your function
bar = str(bar[0])
Bryan
  • 6,682
  • 2
  • 17
  • 21
1

The [1:] syntax is a type of slice; the colon is the key syntactic element that tells us this is the case. Rather than rather a single element, it gives you a section of the list indicated by the indices you specify. For example,

>>> x = [0,1,2,3,4]
>>> x[1:3]
[1, 2]

This is taking the section of the list from index 1 to index 3.

Your code is more like this:

>>> x[1:]
[1, 2, 3, 4]

It takes the element at index 1 and every index following. Because we omitted the ending index, it assumes that we want everything to the end of the list. We could also use negative indices to count backwards from the end of the list:

>>> x[1:-2]
[1, 2]
Community
  • 1
  • 1
jpmc26
  • 28,463
  • 14
  • 94
  • 146
0

If you want to print all command line arguments as a single string without the brackets, you can use the .join() method of a string:

def main(bar):
    bar = ' '.join(bar)
    print bar
main(sys.argv[1:])

This will join all the elements of the list in bar separated by a space, and then place that string back into the variable bar.

If there is only one argument, this will print

bar

But if there are multiple arguments, it will print

bar foo
SethMMorton
  • 45,752
  • 12
  • 65
  • 86