I want to slice by range in Python and it seems like it's not possible.
>>> 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
Why do I want to do this? I want to define "what to slice" in one part of my script, put that in a variable, and do the actual slicing elsewhere. Like this:
myrange=range(1,2)
a='0123456789'
a[myrange] #<-----raises TypeError
Is it possible, and if not, how to do something similar correctly and "right"?
The slice() method returns a portion of an iterable as an object of the slice class based on the specified range. It can be used with string, list, tuple, set, bytes, or range objects or custom class object that implements sequence methods __getitem__() and __len__() methods.
The slicing operation doesn't raise an error if both your start and stop indices are larger than the sequence length. This is in contrast to simple indexing—if you index an element that is out of bounds, Python will throw an index out of bounds error. However, with slicing it simply returns an empty sequence.
The first function takes a single argument while the second function takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection. For example, if we want to get first two elements from the ten element? s list, here slice can be used.
Slicing is the cutting of food into thin, relatively broad slices. Slices may be used as they are or processed further to produce other speciality cuts such as chiffonade, rondelles, diagonals, oblique or roll cuts, and lozenges. Slicing may be accomplished by hand or machine.
Will slice
do instead of range
?
If so, you can use it:
>>> a = '0123456789'
>>> a[slice(1, 2)]
'1'
Try using slice() instead of range()
mySlice=slice(1,2)
a='0123456789'
a[mySlice]
will give you
'1'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With