簡體   English   中英

Python for循環在字符串結尾之前停止

[英]Python for loop stops before end of string

我已經在關於stackoverflow的現有答案中搜索了此問題的解決方案,但無法解決我的問題。

我想遍歷字符串“ 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

我想要得到的輸出是:

WHERESOEVER
YOU
WITH
YOUR
HEART

此后,僅當遇到非字母字符時才打印單詞。 完成對字符串的循環后,還需要打印它。

如果您遍歷單詞而不是每個字符,而只是將結果累加到新列表中,這將簡單得多。

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

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

解釋中的代碼內注釋:

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:隨心所欲

使用以下代碼:

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

使用此代碼幾乎相同。

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'(字母數字)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM