In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45
现在,x的正指数范围是从0到44(即长度-1)
In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/home/<ipython console> in <module>()
IndexError: string index out of range
In [5]: x[44]
Out[5]: 's'
对于负索引,索引范围从-1到-45
In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a
>>> s = "python"
>>> s[3]
'h'
>>> s[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0]
'p'
>>> s[-1]
'n'
>>> s[-6]
'p'
>>> s[-7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>>
现在,x的正指数范围是从0到44(即长度-1)
对于负索引,索引范围从-1到-45
对于负索引,负[长度-1]即正索引的最后一个有效值将给出第二个list元素,因为该列表是按相反顺序读取的
其他,索引的例子
以前的答案是关于某个索引的
ASCII character
。在Python 2的某个索引处获取
Unicode character
有点麻烦。例如,使用
s = '한국中国にっぽん'
,即<type 'str'>
__getitem__
,例如,s[i]
,并不会引导你到达你想要的地方。它会吐出类似�
的符号。(许多Unicode字符超过1个字节,但是Python 2中的__getitem__
增加了1个字节。)在本例Python 2中,可以通过解码来解决问题:
首先确保所需的数字是字符串开头或结尾的有效索引,然后可以简单地使用数组下标表示法。 使用
len(s)
获取字符串长度相关问题 更多 >
编程相关推荐