Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing by range

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"?

like image 613
Karel Bílek Avatar asked Dec 26 '14 17:12

Karel Bílek


People also ask

What is a range slice function in string?

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.

What happen if you use out of range index with slicing?

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.

What is slicing explain with example?

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.

How do you explain slicing?

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.


2 Answers

Will slice do instead of range? If so, you can use it:

>>> a = '0123456789'
>>> a[slice(1, 2)]
'1'
like image 177
ovgolovin Avatar answered Sep 19 '22 13:09

ovgolovin


Try using slice() instead of range()

mySlice=slice(1,2)
a='0123456789'
a[mySlice]

will give you

'1'
like image 24
Bob Haffner Avatar answered Sep 17 '22 13:09

Bob Haffner