mardi 11 septembre 2018

Python - string index out of range issue

i'm an absolute newbie and running into a rather dumb problem :) this is the question I was given to solve: "Create a program inputs a phrase (like a famous quotation) and prints all of the words that start with h-z."

I solved the problem but the first two methods didn't work and I wanted to know why:

#1 string index out of range

quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""

for character in quote:
    if character.isalpha():
        word += character.upper()
    else:
        if word[0].lower() >= "h":
            print(word)
            word = ""
        else: 
            word = ""

: I get the "IndexError: string index out of range" message for any words after "g". Shouldn't the "else" statement catch it? I don't get why it doesn't, because if I remove the brackets [] from word[0], it works.

#2: last word not printing

quote = input("enter a 1 sentence quote, non-alpha separate words: ")
word = ""

for character in quote:
    if character.isalpha():
        word += character.upper()
    else:
        if word.lower() >= "h":
            print(word)
            word = ""
        else: 
            word = ""

: in this example, it works to a degree. it eliminates any words before 'h' and prints words after 'h', but for some reason doesn't print the last word. It doesn't matter what quote i use, it doesn't print the last word even if it's after 'h'. Why is that?

Thank you in advance and would really appreciate your help :)

Aucun commentaire:

Enregistrer un commentaire