问题
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]
回答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
.
回答2:
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.
回答3:
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
来源:https://stackoverflow.com/questions/32884087/slicing-string-from-start