弦乐是字符数据的有序序列。索引允许您使用数值直接访问字符串中的各个字符。字符串索引是零基础:字符串中第一个字符的索引为 0,下一个字符为 1,依此类推。在本课程中,您将学习字符串索引语法并通过几个示例进行练习:
>>>>>> s = 'mybacon'
>>> s[0]
'm'
>>> s[1]
'y'
>>> s[6]
'n'
>>> s[len(s) - 1]
'n'
>>> s[7]
Traceback (most recent call last):
File "<input>", line 1, in <module>
s[7]
IndexError: string index out of range
这是一些负字符串索引:
>>>>>> s
'mybacon'
>>> s[-1]
'n'
>>> s[-4]
'a'
>>> s[-len(s)]
'm'
>>> s[-7]
'm'
>>> s[-8]
Traceback (most recent call last):
File "<input>", line 1, in <module>
s[-8]
IndexError: string index out of range
>>> t = ''
>>> type(t)
<class 'str'>
>>> t[0]
Traceback (most recent call last):
File "<input>", line 1, in <module>
t[0]
IndexError: string index out of range
>>> len(t)
0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)