python - How can I use colon (:) in variable -


this question has answer here:

i want write code this:

index = 0:2 print(list[index]) 

but not work.

is there way can store parts of [...:...] syntax in variable?

you want slice() object:

index = slice(0, 2) print(somelist[index]) 

slice() models start, stop , stride values can specify in [start:stop:stride] subscription syntax, object.

from documentation:

return slice object representing set of indices specified range(start, stop, step). start , step arguments default none. slice objects have read-only data attributes start, stop , step merely return argument values (or default).

under covers, python translates subscriptions slice() object when calling custom __getitem__ methods:

>>> class foo(object): ...     def __getitem__(self, item): ...         return item ... >>> foo()[42:81:7] slice(42, 81, 7) >>> foo()[:42] slice(none, 42, none) 

a viable alternative store start , stop separate values:

startindex = 0 stopindex = 2 print(somelist[start:stop]) 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -