Home > front end >  string slicing in python (meaning of [0:-1])
string slicing in python (meaning of [0:-1])

Time:07-18

I have been referring to a few sources of information on slicing strings (here, for example).

I wanted to understand the behavior of slicing so I tried the following script.

s= 'abc'

print(s[0:1])

print(s[0:-5])

print(s[0:-1])

The source I linked above gave me the following

arr[start:stop]         # items start through stop-1
arr[start:]             # items start through the rest of the array
arr[:stop]              # items from the beginning through stop-1
arr[:]                  # a copy of the whole array
arr[start:stop:step]    # start through not past stop, by step

So, based on the syntax above, I would have thought print(s[0:1]) would result in 'a' but the rest (print(s[0:-5]) and print(s[0:-1]) would result in ''

To my surprise, they resulted in '' and 'ab'.

So I ran the following code:

print(s[0:-4])
print(s[0:-3])
print(s[0:-2])

They printed '','', and 'a', respectively.

I am confused as to how the syntax is working.

P.S. My goal is to set up the slicing such that if the 2nd number ([1st:2nd]) is less than the 1st number, the output is ''.

CodePudding user response:

The negative numbers effectively count from the right. So:-

s[0:-1] 

-:means "every element except the last one in s"

Hence:-

s[0:-5]

-:means "every element except the last five in s"

Since there are not five elements in s, this returns the empty string.

Another example:-

s = "abcdefghijklmnopqrstuvwxyz"
s[8:-3]

-:this is effectively saying "All of the letters in the alphabet except the first eight and the last three".

  • Related