遍历字符串并打印过滤后的单词

3

我卡在了Python课程的一个任务上。我还需要使用Jupyter笔记本,不知道是否会有什么影响。

我需要输入一些内容,遍历并将它们分成单个单词,仅在单词以大于G的字母开头时打印它们。如果不是,则清空该字符串并开始下一个单词。

这是我的代码:

# setting up the variables
quote = ("Wheresoever you go, go with all your heart")
test_quote = quote.lower()
words = " "
# check is the letter is an alphabet; if it is, add it to the empty string
for character in test_quote:
    if character.isalpha():
        words += character
    else:
        # checks if the letter is greater than h; if it is, print it, if not, add a new line
        if words[0] >= "h":
            print(word.upper())
        else:
            print("\n")
    # reset the string
    word = " "

我应该得出以下这个结果:

WHERESOEVER
YOU
WITH
YOUR
HEART

但我得到了(无):



非常感谢您的帮助。

注意:我不认为我被允许使用像.split()这样的函数,您应该能够使用for/in循环、输入、if、else、.isalpha()、.upper()、.lower()、.isupper()和.islower()来完成此任务。


如果您能快速学习如何调试程序代码,那将会非常有帮助。更新您的答案部分(它真的是空的吗?)。 - Jeroen Heier
使用print()来显示变量的值和代码执行的部分信息。这有助于查看问题,被称为“打印调试”。或者学习如何使用真正的调试器。 - furas
提示:你如何初始化“words”?在你这样做之后,“words[0]”是什么?当你附加到“words”时,它会改变这个事实吗?因此,当你比较“words[0] >=“h””时会发生什么? - Karl Knechtel
2个回答

0

这应该可以工作

quote = ("Wheresoever you go, go with all your heart")
quote = quote.upper()
quote = quote.replace(",","")
word = ""
for i in quote:
    if not i == " ":
        word += i
    else:
        inWord = word[0]
        if inWord > 'G':
            print(word)
        word = ""
inWord = word[0]
if inWord > 'G':
    print(word)

1
这样会打印GO,而不是GO吗? - Sayandip Dutta

0

在“单词”和“单词”之间存在问题,而您的重置不正确。尝试这个:

quote = ("Wheresoever you go, go with all your heart")
test_quote = quote.lower()
words = ""
for character in test_quote:
    if character.isalpha():
        words += character
    else:
        if words.isalpha():
            if words[0]>= "h":
                print(words.upper())
        words = ""

if words.isalpha() and words[0]>= "h":
    print(words.upper())

谢谢你的帮助,但我有一个问题:为什么使用“word”作为变量不起作用?变量“word”中是否有一些存储的值?此外,在for循环之后为什么还有另一个.isalpha()和print?如果这些是愚蠢的问题,对不起,我对Python还很陌生。 - GameTheory 345
你已经将字符分配给了“words”变量,并将空格分配给了“word”变量。因此,在打印“word”变量时,会得到很多空格。 - SM Abu Taher Asif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接