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

时间:2019-05-03 04:01:44

标签: python python-3.x

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

这是我编写的代码:

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 = ""

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

5 个答案:

答案 0 :(得分:1)

  • 在您的原始代码中,您有一个,导致代码中断,因为它不是字母数字字符,所以它进入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将字符串拆分为单词,迭代单词,然后检查每个单词的第一个字符是否位于h-z

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

答案 1 :(得分:1)

  

我做错了什么?

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

您可以通过在比较之前检查word是否为空字符串来解决此问题。
更改

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

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

An empty string evaluates to a boolean False

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

andboolean operation;如果任何一项为False,则x and y的评估结果为False-首先评估x;如果它是False,则将返回其值,并且将不评估y。这称为short circuit behavior.

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

False
>>> 

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

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

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

答案 2 :(得分:0)

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

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

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

word = ""
word[0]

IndexError: string index out of range

答案 3 :(得分:0)

请尝试打印以h-z开头的句子的每个单词:

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)

答案 4 :(得分:0)

总是寻求简单的解决方案...

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)