如何通过索引从字符串中获取字符?
假设我有一个字符串,里面有x个不知道的字符。我该怎么才能获取第13个字符或者第x-14个字符呢?
7 个回答
7
之前的回答主要讲了如何在某个位置获取ASCII字符
。
在Python 2中,获取某个位置的Unicode字符
有点麻烦。
比如,假设有一个字符串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]
7
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
对于负数索引,负数索引[length - 1],也就是说正数索引的最后一个有效值会作为列表的第二个元素,因为列表是反向读取的。
In [8]: x[-44]
Out[8]: 'n'
其他索引的例子,
In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'
167
首先,确保你要使用的数字是字符串的有效索引,也就是说这个数字要在字符串的范围内,可以从头开始数或者从尾巴开始数。然后你就可以简单地用数组下标的方式来访问字符串了。你可以用 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
>>>