Dasho
Dasho

Reputation: 3

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

This is a problem I have solved but need to understand why I failed in my first attempt.

The goal is to print words(capitalized), starting from "h" and higher and excluding non-alpha.

The string is: "Wheresoever you go, go with all your heart"

This is my first attempt:

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())

Resulting in:

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

But when I added "if word.isalpha()==True and" it worked:

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

Upvotes: 0

Views: 43

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140178

that's because word is empty at first.

So

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

fails because the first condition triggers an exception (array out of bounds)

Now with:

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

isalpha returns False on empty string so no risk of accessing an out of bounds array (BTW no need to test against True, word.isalpha() alone is enough)

Note that the proper fix is to test "truth" of word first (i.e. test if not empty):

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

Upvotes: 1

Related Questions