2017-12-10 12 views
1

私はこの質問の解決策をstackoverflowの既存の回答の中から探し出し、問題を解決できませんでした。Python forループが文字列の最後の前に停止する

文字列 "quote"を繰り返し、プレースホルダー変数の単語に各単語を格納し、最初の文字がh以上で、次の単語に移動する場合は単語を出力します。

しかし、私のループは最後の単語を反復する前に止まるようです。なぜ誰かが私に理解を助けることができますか?

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 = "" 

私が手出力は次のようになります。

WHERESOEVER 
YOU 
WITH 
YOUR 

私が取得しようとしていますouputをです:インコード

WHERESOEVER 
YOU 
WITH 
YOUR 
HEART 

答えて

0

説明のコメント:

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) 

2.6と3.5用に動作します。

出力: 読み取り専用のbash @:あなたは後の非文字文字に遭遇したときWHERESOEVER YOU YOUR HEART

+2

これは、OPが望んでいない「WHEREESOEVERYOUGOGOWITHALLYOURHEART」を出力します。 –

+0

@MikeScottyはこれを修正します。 –

4

WITHあなただけの単語を印刷します。文字列のループを終了したら、それを印刷する必要があります。

0

利用コード以下:

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) 

結果:あなたは言葉ではなく、各文字を繰り返し処理、およびだけで、結果を蓄積している場合

WHERESOEVER YOU WITH YOUR HEART

3

これがずっと簡単になります新しいリスト。

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

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

このコードはほぼ同じです。

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 = "" 

問題は、引用符の最後の文字が「t」(英数字)であることでした。