可以说我有一个包含x个未知字符的字符串。我怎么能找到char nr。13或char nr。x-14?
Answers:
首先确保所需的数字是从开头或结尾开始的字符串的有效索引,然后可以简单地使用数组下标表示法。用于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
>>>
s[-5]
可以工作,但是s[-6]
会抱怨索引超出范围错误?很好奇Python中字符串对象的实现。
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'
先前的答案涵盖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]
Python.org在这里有很多关于字符串的部分。向下滚动到显示“切片符号”的位置。
这应进一步阐明以下几点:
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