繁体   English   中英

Python中的索引错误:“字符串索引超出范围”

[英]Index error in Python: “string index out of range”

我是一名初学者程序员,作为练习,我想编写一个代码,以将单词中以hz开头的句子中的每个单词打印到新行中。

这是我编写的代码:

random_phrase = "Wheresoever you go, go with all your heart"
word = ""
for ltr in random_phrase:
    if ltr.isalpha():
        word += ltr
    else:
        if word.lower()[0] > "g":
            print(word)
            word = ""
        else:
            word = ""

打印完您后,会有一行空白,然后出现索引错误。 我做错了什么?

  • 在原始代码中,您有一个,由于它不是字母数字字符,所以导致代码中断,因此它进入else循环,其中您的word是一个空字符串,并且在您尝试获取第一个元素时是一个空字符串,则得到IndexError 因此,最好检查非空格字符,例如if ltr != ' ':

  • 您可以重置word = ""if条件

  • 您的代码不会检查字符串中的最后一个单词,您可以在for循环完成后执行此操作

因此,您的重构代码将如下所示

random_phrase = "Wheresoever you go go with all your heart"
word = ""
for ltr in random_phrase:
    #Check for non-whitespace character
    if ltr != ' ':
        word += ltr
    else:
        #Check if word starts with g
        if word.lower()[0] > "g":
            print(word)
        #Reset word variable
        word = ""

#Check the last word
if word.lower()[0] > "g":
    print(word)

输出将是

Wheresoever
you
with
your
heart

通过使用string.split将字符串拆分为单词,迭代单词,然后检查每个单词的第一个字符是否位于hz可以大大简化代码

random_phrase = "Wheresoever you go, go with all your heart"

#Split string into words
words = random_phrase.split()

#Iterate through every word
for word in words:

    #If the first character of the word lies between h-z, print it
    if word.lower()[0] > "g":
        print(word)

这是您的输出

Wheresoever
you
with
your
heart

我做错了什么?

当您的进程在单词go之后遇到逗号(非字母)时,它将确定go的开头不是大于'g'的字母,因此它将为word分配一个空字符串( else; word = '' )。 下一项是非字母的空格,它尝试比较word的第一个字母为空字符串( ''[0] > 'g' )”,从而导致IndexError。

您可以通过在比较之前检查word是否为空字符串来修复它。
更改

if word.lower()[0] > "g":

if word and word.lower()[0] > "g":

空字符串的计算结果为布尔False

>>> s = ''
>>> bool(s)
False
>>>

and布尔操作 ; 如果任一项为False,则x and y评估结果为False首先评估x 如果为False ,则将返回其值,并且将不评估y 这称为短路行为。

>>> x = ''
>>> y = 'foo'
>>> x and y
''
>>> bool(x and y)
False
>>> if x and y:
...     print(True)
... else:
...     print(False)

False
>>> 

我对条件语句的解决方法取决于短路行为,因此,如果word为空字符串,则不会评估word[0]... 您的else子句可以写得更明确-类似于:

....
    else:
        if not word:
            pass
        elif word.lower()[0] > "g":
            print(word)
        word = ""

但由于某种原因,我不喜欢它的外观。

我认为由于此代码段而发生错误:

    if word.lower()[0] > "g":
        print(word)
        word = ""
    else:
        word = ""

您要将word变量重置为空白。 在空白处建立索引不起作用(如您在尝试执行此代码时所看到的):

word = ""
word[0]

IndexError: string index out of range

尝试使用以下命令打印以hz开头的句子的每个单词:

import string
# make the sentence lower case
random_phrase = "Wheresoever you go, go with all your heart".lower()
# split the sentence with space as separator into a list
words = random_phrase.split(" ")
start = "h"
end = "z"
# string.ascii_lowercase will give the lowercase letters ‘abcdefghijklmnopqrstuvwxyz’
letters = string.ascii_lowercase
# take the range h-z
allowed = letters[letters.index(start):letters.index(end)+1]
# iterate through each word and check if it starts with (h-z)
for word in words:
    if any(word.startswith(x) for x in allowed):
        print(word)

使用正则表达式:

import re
random_phrase = "Wheresoever you go, go with all your heart"
words = [s for s in random_phrase.split() if re.match('^[h-z,H-Z]', s)]
for word in words:
    print(word)

始终寻求简单的解决方案...

phrase = "Wheresoever you go, go with all your heart"
for word in (phrase.lower()).split():
   first_letter = word[0]
   if first_letter > "g":
      print(word)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM