Suppose I have a variable S
with the string "1:3"
(or for that matter, "1"
, or "1:"
or ":3"
) and I want to use that as a slice specifier on list L
. You cannot simply do L[S]
since the required args for a slice are "int:int"
.
Now, I current have some ugly code that parses S
into its two constituent int
s and deals with all the edge cases (4 of them) to come up with the correct slice access but this is just plain ugly and unpythonic.
How do I elegantly take string S
and use it as my slice specifier?
Here's another solution
eval("L[%s]" % S)
warning - It's not safe if S is coming from an external(unreliable) source.