ganele892
ganele892

Reputation: 91

Python for loop stops before end of string

I have searched for a solution to this question among the existing answers on stackoverflow and have not been able to resolve my problem.

I want to iterate through the string "quote" and store each word in a placeholder variable word, print the word if the first letter is greater than or equal to h, and at a space move onto the next word.

However my loop seems to stop before iterating through the last word. Could someone help me understand why?

quote = "Wheresoever you go, go with all your heart"
word = ""

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

The output I get is:

WHERESOEVER
YOU
WITH
YOUR

The ouput I am trying to get is:

WHERESOEVER
YOU
WITH
YOUR
HEART

Upvotes: 1

Views: 1026

Answers (5)

Nidheesh
Nidheesh

Reputation: 36

use this code its almost same.

quote = "Wheresoever you go, go with all your heart"
word = ""
quote += " "
for letter in quote:
  if letter.isalpha() == True:
    word = word + letter
  else:
    if word.lower() >= "h":
        print(word.upper()) 
        word = ""
    else:
        word = ""

the problem was that the last character in quote is 't' (an alphanumeric) .

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51653

In-code comments for explanation:

quote = "Wheresoever you go, go with all your heart"
word = ""
sentence = "" # use this to accumulat the correct words    

for letter in quote+"1": 
    # I add a non alpha to your quote to ensure the last word is used or discarded as well
    if letter.isalpha() == True:
        word = word + letter
    else:
        if word.lower() >= "h":
            sentence += word.upper() + " " # add word to sentence you want
            word = "" 
        else: 
            word = "" # discard the word, not starting with h

print (sentence) 

Works for 2.6 and 3.5.

Output: read-only@bash: WHERESOEVER YOU WITH YOUR HEART

Upvotes: 0

chepner
chepner

Reputation: 531175

This would be a lot simpler if you iterated over the words, not each character, and just accumulated the result in a new list.

quote = "Wheresoever you go, go with all your heart"

new_quote = " ".join([word.upper() for word in quote.split() if word.lower() >= "h"])

Upvotes: 3

Ahmad
Ahmad

Reputation: 910

Use following code:

quote = "Wheresoever you go, go with all your heart"
word = ""

quote=quote.split(' ')
for i in quote:
    if(i[0].lower()>='h'):
        word=word+i.upper()+' '
print(word)

Result:

WHERESOEVER YOU WITH YOUR HEART

Upvotes: 0

Marc
Marc

Reputation: 21055

You only print the word when you encounter a non-letter character after. You need to also print it when you're finished looping over the string.

Upvotes: 4

Related Questions