Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何通过索引从字符串中获取字符?_Python_String - Fatal编程技术网

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

Python 如何通过索引从字符串中获取字符?,python,string,Python,String,假设我有一个由x个未知字符组成的字符串。如何获取字符编号13或字符编号x-14?首先确保所需的数字是字符串开头或结尾的有效索引,然后您可以简单地使用数组下标表示法。 使用len获取字符串长度 >>> s = "python" >>> s[3] 'h' >>> s[6] Traceback (most recent call last): File "<stdin>", line 1, in <module> Ind

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

首先确保所需的数字是字符串开头或结尾的有效索引,然后您可以简单地使用数组下标表示法。 使用
len
获取字符串长度

>>> 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=“python”
>>>s[3]
“h”
>>>s[6]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
索引器错误:字符串索引超出范围
>>>s[0]
“p”
>>>s[-1]
“不”
>>>s[-6]
“p”
>>>s[-7]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
索引器错误:字符串索引超出范围
>>> 
现在,x的正指数范围为0到44(即长度-1)

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

In [8]: x[-44]
Out[8]: 'n'
其他,索引的例子,

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

这应进一步澄清以下几点:

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')
a=int(原始输入(“输入索引”)
str1=‘示例’
长度=长度(str1)
如果(a<(len-1))和(a>(-len)):
打印str1[a]
其他:
打印('索引溢出')
投入3 输出m

投入-3
输出p

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

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

0
a
1
b
2
c 

org有一个非常好的关于字符串的部分。向下滚动到显示“切片表示法”的位置。

前面的答案涵盖了特定索引处的
ASCII字符

在Python2中,在某个索引处获取
Unicode字符
有点麻烦

例如,使用
s=한국中国にっぽん'

\uuu getitem\uuu
,例如,
s[i]
,不会引导您到达您想要的地方。它会吐出类似
。(许多Unicode字符超过1个字节,但Python 2中的
\uuu getitem\uuu
增加1个字节。)

在这个Python 2案例中,您可以通过解码来解决问题:

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

我认为这比用文字描述要清楚得多

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

你可以传负片integers@AviramSegal感谢您的更正,是的,我们可以,但它们也应该在字符串长度的限制范围内。编辑后,它是最佳答案,投票结果是向上而不是向下:)此答案可以通过在每个索引处使用具有唯一字符的不同单词来改进。就目前情况而言,s[3]返回的“l”不明确。为什么
s[-5]
可以工作,但
s[-6]
会抱怨索引超出范围错误?对Python中字符串对象的实现非常好奇。你应该提供一些口头描述,说明发生了什么,尽管这个问题对你来说可能很基本。用一些描述更新了答案,希望有帮助:)
L = ['a', 'b', 'c']
for index, item in enumerate(L):
    print index + '\n' + item

0
a
1
b
2
c 
s = '한국中国にっぽん'
s = s.decode('utf-8')
for i in range(len(s)):
    print s[i]
s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'