假设我有一个由x个未知字符组成的字符串。如何获取第13个字符或第x-14个字符?
首先确保所需数字是字符串的有效索引,可以从开头或结尾开始,然后您可以简单地使用数组下标符号。
使用 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
>>>
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'
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'
之前的答案涵盖了关于某个索引处的 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]
另一个推荐的练习是理解列表和索引:
L = ['a', 'b', 'c']
for index, item in enumerate(L):
print index + '\n' + item
0
a
1
b
2
c
我认为这样比用言语描述更清晰
s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'
这应该进一步澄清这些观点:
a = int(raw_input('Enter the index'))
str1 = 'Example'
leng = len(str1)
if (a < (len-1)) and (a > (-len)):
print str1[a]
else:
print('Index overflow')
输入 3 输出 m
输入 -3 输出 p
s[-5]
可以工作,但是s[-6]
会报索引超出范围的错误? 对Python中字符串对象的实现非常好奇。 - Alston