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


91

可以说我有一个包含x个未知字符的字符串。我怎么能找到char nr。13或char nr。x-14?

Answers:


128

首先确保所需的数字是从开头或结尾开始的字符串的有效索引,然后可以简单地使用数组下标表示法。用于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 2012年

@AviramSegal感谢您的纠正,是的,但是它们也应该在字符串长度的范围内。
DhruvPathak 2012年

1
编辑最佳答案后,请投票赞成而不是
反对

1
通过在每个索引处使用带有唯一字符的不同单词可以改善此答案。就目前而言,s [3]对于返回的是“ l”是模棱两可的。
善待新用户

1
为什么s[-5]可以工作,但是s[-6]会抱怨索引超出范围错误?很好奇Python中字符串对象的实现。
Alston

5
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 2012年

3

先前的答案涵盖ASCII character了一定的索引。

Unicode character在Python 2中获得某个索引有点麻烦。

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

__getitem__,例如,s[i]不会将您带到您想要的地方。它会吐出类似的东西。(许多Unicode字符超过1个字节,但__getitem__在Python 2中增加了1个字节。)

在这种Python 2情况下,可以通过解码解决问题:

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


1

为理解列表和索引而推荐的另一项练习:

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

0
a
1
b
2
c 

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


0

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

s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.