Dhr*_*hak 117
首先确保所需的数字是从开头或结尾开始的字符串的有效索引,然后您可以简单地使用数组下标表示法.使用len(s)
得到的字符串长度
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
以前的答案涵盖了ASCII character
某个索引。
Unicode character
在Python 2中获取某个索引处的a有点麻烦。
例如,其中s = '\xed\x95\x9c\xea\xb5\xad\xe4\xb8\xad\xe5\x9b\xbd\xe3\x81\xab\xe3\x81\xa3\xe3\x81\xbd\xe3\x82\x93'
是<type 'str'>
,
__getitem__
,例如s[i]
, 不会引导您到达您想要的地方。它会吐出类似的东西\xef\xbf\xbd
。(许多 Unicode 字符都超过 1 个字节,但__getitem__
在 Python 2 中会增加 1 个字节。)
在这个Python 2案例中,你可以通过解码来解决问题:
\n\ns = '\xed\x95\x9c\xea\xb5\xad\xe4\xb8\xad\xe5\x9b\xbd\xe3\x81\xab\xe3\x81\xa3\xe3\x81\xbd\xe3\x82\x93'\ns = s.decode('utf-8')\nfor i in range(len(s)):\n print s[i]\n
Run Code Online (Sandbox Code Playgroud)\n
In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45
Run Code Online (Sandbox Code Playgroud)
现在,对于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'
Run Code Online (Sandbox Code Playgroud)
对于负指数,指数范围从-1到-45
In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a
Run Code Online (Sandbox Code Playgroud)
对于负索引,负[长度-1]即正索引的最后一个有效值将给出第二个列表元素,因为列表以相反顺序读取,
In [8]: x[-44]
Out[8]: 'n'
Run Code Online (Sandbox Code Playgroud)
其他索引的例子,
In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
337727 次 |
最近记录: |