我在一本Python教材中遇到了一个示例,它使用word[1:2]
来切片字符串。它这样做是为了演示只有字符串的一个字母被切片。
这让我想到 - 是否有用例可以使用word[1:2]
而不是仅仅使用word[1]
,因为它们返回相同的结果?
>>> s = "x"
>>> s[1:2]
''
>>> s[1]
IndexError: string index out of range
>>> b'xyz'[1]
121
>>> b'xyz'[1:2]
b'y'
>>> word = 'asdf'
>>> word[1:2]
's'
>>> word[1]
's'
>>> word = ['a', 's', 'd', 'f']
>>> word[1:2]
['s']
>>> word[1]
's'
''[1]
会引发 IndexError
,而 ''[1:2]
则返回一个空字符串。 - DeepSpaceword[1]
与word[1:2]
是不同的。 word[1]
返回索引为1的列表项的值。但word[1:2]
是一个列表切片,它返回位置为1的列表。
word = ['a', 'b', 'c']
print(word[1])
#output: b
#but also
print(word[1:2])
#output: ['b']
word
是一个列表,那么一个将返回一个列表,而另一个则不会。 - DeepSpace