使用单词[1:2],而不只是单词[1]?

问题描述 投票:1回答:1

[我在Python教科书中遇到了一个使用word[1:2]分割字符串的示例。这样做是为了证明只对字符串的一个字母进行切片。

让我开始思考-有没有用例可以使用word[1:2]而不是仅返回返回相同结果的word[1]

python string slice
1个回答
3
投票

对于字符串切片,没有区别,因为字符串的单个元素本身仍然是字符串(即,“字符”和一个字符长的字符串之间没有区别)。

>>> word = 'asdf'
>>> word[1:2]
's'
>>> word[1]
's'

对于其他可分割对象(例如,列表),两者可能不相等:

>>> word = ['a', 's', 'd', 'f']
>>> word[1:2]
['s']
>>> word[1]
's'

1
投票

与其他答案相反,字符串也有所不同。切片不能抛出IndexError

>>> s = "x"
>>> s[1:2]
''
>>> s[1]
IndexError: string index out of range
© www.soinside.com 2019 - 2024. All rights reserved.