Python for循环在字符串

时间:2017-12-10 15:15:50

标签: python for-loop

我已经在stackoverflow的现有答案中搜索了这个问题的解决方案,并且无法解决我的问题。

我想迭代字符串"引用"并将每个单词存储在占位符变量字中,如果第一个字母大于或等于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

5 个答案:

答案 0 :(得分:4)

您只能在遇到非字母字符后打印该单词。完成字符串循环后,还需要打印它。

答案 1 :(得分:3)

如果你迭代单词而不是每个字符,并且只是将结果累积到新列表中,这将会更加简单。

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

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

答案 2 :(得分: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:不管你的心脏什么

答案 3 :(得分:0)

使用以下代码:

WHERESOEVER YOU WITH YOUR HEART

结果:

and

答案 4 :(得分: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'(字母数字)。