create string that represent as slice
Question:
it is possible to use string for slice the list?
i have example like this
m = [1,2,3,4,5]
print(m[:-1])
print(m[1:-1:])
print(m[::2])
above code will result
[1, 2, 3, 4]
[2, 3, 4]
[1, 3, 5]
so i want use string to do something like that
m = [1,2,3,4,5]
inp = input('slice the list ')
#and user will input [:-1], [1:-1:], or [::2]
#slice the list using that input
#m[inp]??
if this possible, how to make this approach?
i cannot find answer for this anywhere or i just don’t know what keyword should i type for search this
Answers:
You can build a slice
object and use that as an arg to the []
operator (or equivalent __getitem__
magic method). slice
takes optional int
arguments (or None
to use the defaults) that correspond to the numbers in the -1:1:
syntax.
So if you want to parse a string like [1:-1:]
without directly using eval
(which can be dangerous since it will also parse all sorts of other expressions), you can do something along the lines of:
- strip the
[]
characters
- split on
:
- pass the
:
-separated numbers as args to slice()
, using None
for missing numbers.
E.g.:
>>> inp = "[1:-1:]"
>>> inp_slice = slice(*(int(i) if i else None for i in inp.strip("[]").split(":")))
>>> [1,2,3,4,5][inp_slice]
[2, 3, 4]
Once you understand how the slice
object works, you’re of course free to accept the input from the user in other forms (e.g. there’s no reason to require them to input the []
part if you know that the input is always going to be used to slice a list).
it is possible to use string for slice the list?
i have example like this
m = [1,2,3,4,5]
print(m[:-1])
print(m[1:-1:])
print(m[::2])
above code will result
[1, 2, 3, 4]
[2, 3, 4]
[1, 3, 5]
so i want use string to do something like that
m = [1,2,3,4,5]
inp = input('slice the list ')
#and user will input [:-1], [1:-1:], or [::2]
#slice the list using that input
#m[inp]??
if this possible, how to make this approach?
i cannot find answer for this anywhere or i just don’t know what keyword should i type for search this
You can build a slice
object and use that as an arg to the []
operator (or equivalent __getitem__
magic method). slice
takes optional int
arguments (or None
to use the defaults) that correspond to the numbers in the -1:1:
syntax.
So if you want to parse a string like [1:-1:]
without directly using eval
(which can be dangerous since it will also parse all sorts of other expressions), you can do something along the lines of:
- strip the
[]
characters - split on
:
- pass the
:
-separated numbers as args toslice()
, usingNone
for missing numbers.
E.g.:
>>> inp = "[1:-1:]"
>>> inp_slice = slice(*(int(i) if i else None for i in inp.strip("[]").split(":")))
>>> [1,2,3,4,5][inp_slice]
[2, 3, 4]
Once you understand how the slice
object works, you’re of course free to accept the input from the user in other forms (e.g. there’s no reason to require them to input the []
part if you know that the input is always going to be used to slice a list).