2012-01-13 107 views

回答

80

首先确保所需的数字是有效索引作为字符串从开始或结束,然后您可以简单地使用数组下标记法。 使用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 
>>> 
+1

可以传递负整数 – 2012-01-13 09:30:32

+0

@AviramSegal感谢您的纠正,是的,我们可以,但他们也应该在字符串长度的限制。 – DhruvPathak 2012-01-13 09:39:55

+1

在你编辑它的最佳答案之后,投票决定而不是down :) – 2012-01-13 09:41:43

5
In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#[email protected]" 
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]即最后一个有效的val作为列表被以相反的顺序读出正折射率的UE将给予第二列表元素,

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

其他,索引的例子中,

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

你应该提供一些关于发生的事情的口头描述,尽管这个问题对你来说似乎很基本。 – Hannele 2012-01-24 20:54:35

+0

更新了一些描述的答案,希望它有助于:) – avasal 2012-01-25 03:43:11

0

这应当进一步明确点:

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

1

另一个推荐名单的理解和索引exersice:

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

0 
a 
1 
b 
2 
c 
3

Python.org有串here一个优秀的部分。向下滚动到“切片符号”所在的位置。

0

以前的答案覆盖了某个指数的ASCII character

这是一个有点麻烦在一定的指数在Python获得Unicode character 2.

例如,与s = '한국中国にっぽん'这是<type 'str'>

__getitem__,例如,s[i],不会导致你的地方你的愿望。它会吐出像这样的东西。 (许多Unicode字符超过1个字节,但在Python 2 __getitem__以1个字节递增。)

在这条巨蟒2的情况下,可以通过解码解决的问题:

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