2

In Python:

s = "Gwen Stefani"
a = s[:0]
b = s[0]

print type(a) # str
print type(b) # str
print len(a)  # 0
print len(b)  # 1

I understand that s[:0] is empty, but it also means from the start of the string so I would have thought that:

s[:0] is the same as s[0]
spenibus
  • 4,339
  • 11
  • 26
  • 35
Mr Mystery Guest
  • 1,464
  • 1
  • 18
  • 47
  • [:0] mean you take 0 character from the beginning. [0] means you take the first character. – Baart Oct 01 '15 at 09:33
  • Because `a = ""` and `b = "G"`, that;s why the type of both is `str` but the `len()` is `0`, `1` resp. – ZdaR Oct 01 '15 at 09:33
  • `s[0:0] ==s[:0] means from 0 to 0` – The6thSense Oct 01 '15 at 09:35
  • `s[:0]` is the substring starting at the start of the string to the char of position 0 (not included) so it's the empty string, `s[0]` is the character at position 0 so it's "G" – Max Oct 01 '15 at 09:40

3 Answers3

1

You can read about the behaviour of string slicing at https://docs.python.org/2/tutorial/introduction.html#strings, which includes an illustration of how to interpret indices.

In particular, it states:

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

(Emphasis mine)

When i and j are both 0 (and i defaults to 0 if not specified), there are no characters between them, so the resulting substring is the empty string, "", which has type str and length 0.

Andrew
  • 5,212
  • 1
  • 22
  • 40
0

You have to understand what slicing does:

x = s[:n]

now, x contains values of s[0],s[1],...,s[n-1], but not s[n]

So, s[:0] returns values from index 0 ,to index before 0, which is nothing.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
0

The last index you take is the one before the specified number, that is: a[x:y] means from x to y-1:

In [4]: s[0:3]
Out[4]: 'Gwe'

So you are not taking from zero to zero, you are taking from zero to minus one, which is empty

Jfreixa
  • 81
  • 7