我想在 Python 中按范围切片,但似乎不可能。
>>> a='0123456789'
>>> a[range(1,2)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers, not list
我为什么要这样做?我想在我的脚本的一部分中定义“要切片的内容”,将其放入一个变量中,然后在其他地方进行实际切片。像这样:
myrange=range(1,2)
a='0123456789'
a[myrange] #<-----raises TypeError
是否可能,如果不可能,如何正确且“正确”地做类似的事情?
最佳答案
slice
会代替 range
吗?
如果是这样,您可以使用它:
>>> a = '0123456789'
>>> a[slice(1, 2)]
'1'
关于python - 按范围切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27659944/