如何循环字符串中的字符,打印以特定字符开头的单词?

How to loop characters in a string, printing words starting with certain character?

这是我已经解决的问题,但需要了解我第一次尝试失败的原因。

目标是打印单词(大写),从 "h" 开始,不包括非字母。

字符串是:"Wheresoever you go, go with all your heart"

这是我的第一次尝试:

quote = input("Enter a quote: ")
word=""
for x in quote:
if x.isalpha()==True and len(x)>0:
    word+=x.lower()
else:
    if word[0]>="h" and len(word)>0:
        print(word.upper())
        word=""
    else:
        word=""

if word[0]>="h" and len(word)>0:
print(word.upper())

导致:

Enter a quote: Wheresoever you go, go with all your heart
WHERESOEVER
YOU
Traceback (most recent call last):
  File "/home/dubirka/PycharmProjects/dasho-project/dasho-
beginner.py", line 7, in <module>
    if word[0]>="h" and len(word)>0:
IndexError: string index out of range

Process finished with exit code 1

但是当我添加 "if word.isalpha()==True and" 时它起作用了:

    else:
        if word.isalpha()==True and word[0]>="h" and len(word)>0:
            print(word.upper())
            word=""
    else:
        word=""

那是因为 word 一开始是空的。

所以

if word[0]>="h" and len(word)>0:

失败,因为第一个条件触发异常(数组越界)

现在:

if word.isalpha()==True and word[0]>="h" and len(word)>0:

isalpha returns False 在空字符串上,因此没有访问越界数组的风险(顺便说一句,无需针对 True、[=17= 进行测试]一个人就够了)

请注意,正确的解决方法是先测试 word 的 "truth"(即测试是否为空):

if word and word[0]>="h":