0

The word Hello contains 5 characters.

>>> x = 'Hello'
>>>
>>> len(x)
5
>>>

x[5] will produce an error as Python number is started from 0. I can understand this.

>>> x[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> 

>>> x[0]
'H'
>>> 

And last charactor is at x[4]

>>> x[4]
'o'
>>> 

However, when I try a range which is from x[0:4], the last letter is not there.

>>> x[0:4]
'Hell'
>>> 

May I know why?

clubby789
  • 2,543
  • 4
  • 16
  • 32

4 Answers4

1

Slicing from 0 to 4 will produce items 0, 1, 2, and 3. If you want to include the las one use

x[0:5]
josoler
  • 1,393
  • 9
  • 15
1
x[0:4]

means

index 4 is excluded.

There is a rationale behind that. You can just substract the two numbers to calculate the length of outcome. :)

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
1

In slicing, first int is included while last is excluded

1

I believe the reason is the way most of those operations are performed:

for(x=start;x<end;x++){
   output[x]=input[x]
}

(pardon my C).

Another reason is consistency between slice operator and len. It's believed that a[0:len(a)] should return a.

George Shuklin
  • 6,952
  • 10
  • 39
  • 80
  • Thanks @George. Would it be possible to view the actual source code of this slicing technique in Python? If yes, please let me know how or where is the actual code. –  Aug 08 '19 at 23:56