英文:
Python sys.argv to remove single quotes (')
问题
trial_id [123, 412, 351, 236]
英文:
I need to pass an argument to trial_id as follow: trial_id [123, 412, 351, 236]
For some reason, after argument is passed, single quotes are added and breaks my code.
Python command is python3 pull_t3.py 123,412,351,236
trial_ids = [sys.argv[1]]
print("trial_id", trial_ids)
prints
trial_id ['123,412,351,236']
How can I remove single quotes (')? I would prefer the python sys argument does not change. Rater something in the code.
答案1
得分: 0
以下是翻译好的部分:
当您以您刚才所做的方式传递参数运行文件时,您只传递了一个参数。一个字符串。这就是输出返回给您的内容。
python3 pull_t3.py 123,412,351,236
所以,如果您想传递多个参数,您需要用空格分隔每个参数,而不是用逗号。就像这样:
python3 pull_t3.py 123 412 351 236
现在,您需要在脚本中进行的更正如下:
现在您正在传递多个参数,它们将在argv[1],argv[2]...等位置可访问。您可以像这样切片列表:
trial_ids = sys.argv[1:]
这将获取您运行文件时的每个参数。
您的输出现在将类似于:
trial_id ['123', '412', '351', '236']
现在,每个参数都作为单独的字符串存在。然后,您可以使用类似以下的列表理解轻松将列表中的所有元素转换为整数:
trial_ids = [int(i) for i in trial_ids]
希望这解决了您的问题。
英文:
When you run the file with the arguments like the way you just did, you have only passed in one argument. A single string. And that's what the output gives back to you.
python3 pull_t3.py 123,412,351,236
So, if you want to pass in multiple arguments, you separate each argument with a whitespace, and not a comma. Like so:
python3 pull_t3.py 123 412 351 236
Now, the correction you'll have to make in your script for that is this:
Now that you're passing in multiple arguments, they'll be accessible at argv[1], argv[2]... etc. So you can just slice the list like so:
trial_ids = sys.argv[1:]
That takes every argument you run the file with.
Your output will now look something like this:
trial_id ['123', '412', '351', '236']
You now have each argument as a separate String. You can then easily convert all elements in the list to ints with a list comprehension like this:
trial_ids = [int(i) for i in trial_ids]
Hope that resolves your issue
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论