Python中使用sys.argv[1, :5]截断命令行参数报错,问题出在哪?
sys.argv[1, :5] cause an error in Python? Hey there! Let's break down exactly what's going wrong with that line of code.
First, a quick recap: sys.argv is a list where each element represents a command-line argument passed to your script. When you run python stub.py 123456789, sys.argv[1] correctly grabs the string "123456789" — that part you had right with your temp = sys.argv[1] line.
The issue with sys.argv[1, :5] boils down to invalid Python syntax for how lists and string slicing work:
- You can't use a tuple (
1, :5) as an index for a list. Lists only accept single integer indexes (like[1]) or slice notation for ranges of list elements (like[0:2]to get the first two elements of the list). - The
[:5]slicing works on strings (which is whytemp[:5]works perfectly), but you need to first pull the string element from the list, then apply the slice to that string — not try to combine both operations in one list index.
Fixing the code
Instead of sys.argv[1, :5], you need to chain the operations: first access the 1st element from the sys.argv list, then slice that resulting string. The corrected line looks like this:
print(sys.argv[1][:5])
Here's your full working code for reference:
#! /usr/bin/env python import sys temp = sys.argv[1] print(temp) print(temp[:5]) print(sys.argv[1][:5]) # Fixed line
When you run this with python stub.py 123456789, it will output:
123456789 12345 12345
To wrap it up:
sys.argvis a list of strings- Use
sys.argv[1]to fetch the first command-line argument (as a string) - Apply string slicing (
[:5]) directly to that string result, not inside the list index
内容的提问来源于stack exchange,提问作者flywire

