2

I am new to Python. I'm running Raspbian and calling a Python script this way:

python testarguments.py "Here is a test parameter"

My script:

import sys
print sys.argv[1:]

Output:

['Here is a test parameter']

Question: What is the most efficient way to remove beginning and ending brackets and single quotes from sys.argv output?

JamieHoward
  • 693
  • 2
  • 11
  • 27

3 Answers3

2

You are slicing with

sys.argv[1:]

It means that get all the elements from 1 till the end of the sequence. That is why it creates a new list.

To get only the first item, simply do

sys.argv[1]

This will get the element at index 1.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

The : sort of means 'and onwards' so it of course will return a list. Just do:

>>> sys.argv[1]
'Here is a test parameter'

Thus returning your first argument to executing the program, not a part of the list.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
0

The other answers have addressed the actual issue for you, but in case you ever do encounter a string that contains characters you want to remove (like square brackets, for example), you could do the following:

my_str = "['Here is a test parameter']"
my_str.translate(None, "[]")

In other words, if the output you saw were actually a string, you could use the translate method to get what you wanted.

Nicholas Flees
  • 1,943
  • 3
  • 22
  • 30