gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:56:45 25 4
gpt4 key购买 nike

我在 Python 类(class)中遇到了一项任务。我还必须使用 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()。

最佳答案

这应该可行

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)

关于python - 遍历字符串并打印过滤后的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57352237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com