尝试检索特定字母时出现索引错误

时间:2019-04-21 06:22:32

标签: python

我是一名会计师,也是编码的初学者。我试图了解索引的工作方式。我正在尝试提取字符串中的第二个字母。

def myfuncs(words):
    for chars in words:
        b = chars[1]
        return b  

b = chars[0]时,将显示第一个字母。但是,当我将值更改为任何其他数字b = chars[1]b = chars[2]时,会收到错误“字符串索引超出范围” 。怎么了?机器如何查看我的代码?

2 个答案:

答案 0 :(得分:1)

如果words是一个字符串,那么char只会是该字符串的一个字符,因为for循环只是遍历整个字符串,因此不会在字符串后面附加任何内容char[]。它只是暂时将字符串的当前单个字符存储在char中,因为其中只有一个值,并且索引从0开始; char[1]将是无效点,因为除该单个字符外没有其他数据。

现在,如果要将字符串的每个元素存储在char中,则需要添加以下行:

char_list =[]
for char in words.split():
    char_list.append(char)

#or

char_list = [ char for char in open('the_textfile.txt').read()]

现在您可以访问char_list的第二个第4或第n个位置(n是字符串的长度)

答案 1 :(得分:0)

您的函数将遍历“单词”字符串中的每个字符。因此chars [1]将给出错误。为了您的理解,让我们使用枚举遍历“单词” 让words = "BLA bla βλα"

def myfuncs(words):
    for i,chars in enumerate(words):
        print(i,chars)

words = "BLA bla βλα"
myfuncs(words)

输出将为

0 B
1 L
2 A
3  
4 b
5 l
6 a
7  
8 β
9 λ
10 α

要遍历单词中的每个单词,请使用words.split(),它将在空白处拆分“单词”并返回列表字符串

def myfuncs_1(words):
    words=words.split()
    print('words.split() returns:',words)
    for i,chars in enumerate(words):
        print(i,chars)

words = "BLA bla βλα"
myfuncs_1(words)

输出:

words.split() returns: ['BLA', 'bla', 'βλα']
0 BLA
1 bla
2 βλα

如果只想使用“单词”中第一个字符串的第二个字母

def myfuncs_2(words):    
for i,chars in enumerate(words.split()):
    b = chars[1]
    return b

words = "BLA bla βλα"
print(myfuncs_2(words)) 

这将输出L

如果要使用“单词”中所有字符串的第二个字母,请使用

def myfuncs_3(words):
    b=[]
    for i,chars in enumerate(words.split()):
        b.append(chars[1])
    return b

words = "BLA bla βλα"
print(myfuncs_3(words))

输出将为:['L', 'l', 'λ']