首页 > 解决方案 > Python 中的索引错误:“字符串索引超出范围”

问题描述

我是一名初学者程序员,作为练习,我想编写一个代码,将句子中的每个单词打印到一个新行中,因为该单词以 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 = ""

在它打印你之后,有一行空白,然后发生索引错误。我做错了什么?

标签: pythonpython-3.x

解决方案


试试这个打印以 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)

推荐阅读