【发布时间】:2017-07-05 02:09:22
【问题描述】:
我的任务是打印句子中首字母在一个字母范围内的所有单词,例如:h-z。
到目前为止,这是我的代码,但是它仍然打印以“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()
【问题讨论】:
标签: python python-3.x string