如何按索引从字符串中获取字符?

2024-04-25 09:11:03 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答
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

对于负索引,负[长度-1]即正索引的最后一个有效值将给出第二个list元素,因为该列表是按相反顺序读取的

In [8]: x[-44]
Out[8]: 'n'

其他,索引的例子

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

以前的答案是关于某个索引的ASCII character

在Python 2的某个索引处获取Unicode character有点麻烦。

例如,使用s = '한국中国にっぽん',即<type 'str'>

__getitem__,例如,s[i],并不会引导你到达你想要的地方。它会吐出类似的符号。(许多Unicode字符超过1个字节,但是Python 2中的__getitem__增加了1个字节。)

在本例Python 2中,可以通过解码来解决问题:

s = '한국中国にっぽん'
s = s.decode('utf-8')
for i in range(len(s)):
    print s[i]

首先确保所需的数字是字符串开头或结尾的有效索引,然后可以简单地使用数组下标表示法。 使用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
>>> 

相关问题 更多 >