[英]Remove brackets from argv string
I am new to Python. 我是Python的新手。 I'm running Raspbian and calling a Python script this way:
我正在运行Raspbian并以这种方式调用Python脚本:
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? 问题:从
sys.argv
输出中删除开始和结束括号和单引号的最有效方法是什么?
The :
sort of means 'and onwards' so it of course will return a list
. :
有点'和以后',所以它当然会返回一个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. 这意味着获取从1到序列结束的所有元素。 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. 这将获得索引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. 换句话说,如果您看到的输出实际上是一个字符串,您可以使用translate方法来获得您想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.