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

2024-10-04 09:20:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个我已经解决的问题,但我需要理解为什么我在我的第一次尝试失败

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

这句话的意思是:“无论你走到哪里,都要全心投入”

这是我的第一次尝试:

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”和“it worked:

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

Tags: andintruegolenifwithupper
1条回答
网友
1楼 · 发布于 2024-10-04 09:20:13

那是因为word一开始是空的

所以呢

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

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

现在使用:

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

isalpha返回空字符串上的False,因此没有访问越界数组的风险(顺便说一句,不需要对True进行测试,word.isalpha()就足够了)

注意,正确的解决方法是首先测试word的“真值”(即,如果不是空的话进行测试):

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

相关问题 更多 >