0

I was just confused why in the following example the number on the left is included, while the number on the right isn't:

a = "0123456789"
a[:]  # "0123456789"
a[1:]  # "123456789" -> includes the 1
# and this confuses me:
a[:5]  # "01234" -> excludes the 5
a[1:5]  # "1234" -> again

Can anybody explain why it is designed this way?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
MoPaMo
  • 517
  • 6
  • 24
  • Python as other programming languages start counting from zero, therefore 4 is the 5th and last element from left. – Hermann12 Feb 03 '23 at 17:37
  • A nice explanation, [why](https://skillcrush.com/blog/why-programmers-start-counting-at-zero/) – Hermann12 Feb 03 '23 at 17:43
  • If it helps, the colon isn't an operator, it's just part of the slicing syntax. You can find a list of operators under [Operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) in the docs. – wjandrea Feb 03 '23 at 17:51

1 Answers1

0

You are slicing a string!

A slice operation starts with index 0

In python a slice operation is of format [start:stop:step]

Keep a example string as MyString = "Hi MoPaMo"
Here the first letter has the index as 0
Hi MoPaMo
012345678

So print(MyString[0:4]) is going to output the 1st 4 index numbers
Hi M
0123
From Index 0 to index 4

a="0123456789"
So in a[:]       you are telling there is no start or stop, print everything
In print(a[1:])  you are telling start from index 1
In print(a[:5])  you are telling stop at index 5, therefore it prints 01234
In print(a[1:5]) you are telling to start at index 1 and stop at index 5 which results in 1234

print(a[1:8:2]) is going to print 1357
Here you are telling to skip alternate elements

Do check out this doc Pythons String Doc

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Especially relevant from the tutorial is the bit from "Note how the start is always included, and the end always excluded." up to (but not including :-P) "For non-negative indices" – Jasmijn Feb 03 '23 at 17:48