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

114

假设我有一个由x个未知字符组成的字符串。如何获取第13个字符或第x-14个字符?

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

1
您可以传递负整数。 - Aviram Segal
@AviramSegal 感谢您的纠正,是的,我们可以这样做,但它们也应该在字符串长度的限制范围内。 - DhruvPathak
1
在您进行编辑之后,这是最佳答案,被投票赞成而不是反对 :) - Aviram Segal
1
这个答案可以通过使用每个索引具有唯一字符的不同单词来改进。目前,s [3] 不清楚它返回哪个“l”。 - Be Kind To New Users
1
为什么s[-5]可以工作,但是s[-6]会报索引超出范围的错误? 对Python中字符串对象的实现非常好奇。 - Alston

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'

即使问题对你来说似乎很基础,你也应该提供一些口头描述正在发生的事情。 - Hannele
更新了答案并附上了一些描述,希望能有所帮助 :) - avasal

6

之前的答案涵盖了关于某个索引处的 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]

2

Python.org网站有一个关于字符串的优秀章节,点击这里。请向下滚动到“切片符号”部分。


1

另一个推荐的练习是理解列表和索引:

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

0
a
1
b
2
c 

1

我认为这样比用言语描述更清晰

s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接