如何通过索引从string获取char?

可以说我有一个由x个未知字符组成的string。 我怎么能得到字符。 13或char nr。 X-14?

首先确保所需的数字是从开始或结束的string的有效索引 ,然后您可以简单地使用数组下标符号。 使用len(s)来获取string长度

 >>> 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' 

对于负数索引,索引范围从-1到-45

 In [6]: x[-1] Out[6]: 's' In [7]: x[-45] Out[7]: 'a 

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

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

其他,索引的例子,

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

Python.org在这里有一个很好的关于string的部分。 向下滚动到“切片符号”所在的位置。

理解列表和索引的另一个推荐的方法是:

 L = ['a', 'b', 'c'] for index, item in enumerate(L): print index + '\n' + item 0 a 1 b 2 c 

这应该进一步澄清几点:

 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') 

input3输出m

input-3输出p