我的任务是打印首字母在字母范围内的句子中的所有单词,例如:hz。
到目前为止,这是我的代码,但是它仍然打印以“g”开头的单词并且不打印最后一个单词。
famous_quote = input("Enter a one sentence quote: ").lower()
word = ""
for ltr in famous_quote:
if ltr.isalpha() == True:
word = word + ltr
else:
if word > "g":
print(word)
word = ""
else:
word = ""
我只被允许使用 ASCII 比较,我试图比较 ASCII 值,但我不知道在这种情况下如何去做。
示例输入:
Wheresoever you go, go with all your heart
示例输出:
WHERESOEVER
YOU
WITH
YOUR
HEART
我提出的算法:
- split the words by building a placeholder variable: word
- Loop each character in the input string
- check if character is a letter
- add a letter to word each loop until a non-alpha char is encountered
- if character is alpha
- add character to word
- non-alpha detected (space, punctuation, digit,...) defines the end of a word and goes to else
- else
- check if word is greater than "g" alphabetically
- print word
- set word = empty string
- or else
- set word = empty string and build the next word
- Hint: use .lower()
原文由 fortiswdg 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可以定义一个简洁的小生成器来将你的句子分成单词并比较每个单词的第一个字母。