简体   繁体   中英

Remove brackets from argv string

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM