.isalpha 和 elif 是如何工作的? (python)

how does .isalpha and elif works ? (python)

我想创建一个代码来打印句子中的大写单词(在 "G" 之后)

# [] create words after "G"
# sample quote "Wheresoever you go, go with all your heart" ~ Confucius (551 BC - 479 BC)

# Sample output:

WHERESOEVER
YOU
WITH
YOUR
HEART

这是我的代码

q = input ("Quote : ")

word = ""
for a in q :
    if a.isalpha() == True :
        word = word + a
    elif word[0].lower() > "g" :
        print (word.upper())
        word = ""
    else :
        word = ""

直到句子的最后一个单词都运行良好,尽管第一个字母在"G"之后,但它无法打印单词。此外,当它找到标点符号时,它卡住了,并说

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-45-29b3e8e00230> in <module>()
      8     if a.isalpha() == True :
      9         word = word + a
---> 10     elif word[0].lower() > "g" :
     11         print (word.upper())
     12         word = ""

IndexError: string index out of range

我怀疑它与 .isalphaelif

有关系

我需要知道如何修复它以及我在哪里出错

如果连续有两个不是字母的字符(例如逗号后跟 space),那么当 word 为空字符串时,您将命中 elif word[0].lower() > "g" , 所以 word[0] 处没有字符。这就是导致异常的原因。

简单地说,您可以通过在尝试获取 word[0].

之前检查 word 是否为空来避免这种情况
elif word and word[0].lower() > "g":

那至少应该避免异常。


But I still have the last word issue, it doesn't print the last word although it started with alphabet greater than "G"

只有当您点击非字母字符时才会打印。所以如果你传了一个词,然后不打非字母字符,那么最后一个词就不会被打印出来。

为了解决这个问题,您可以在循环结束后添加一个 print,以防还有最后一个字要打印。

for a in q:
    ... etc.

if word and word[0].lower() > 'g':
    print(word)

你会遇到两个问题

1) 在 word[0] 为空字符串时访问它。 当你有连续的非字母表时会报错。 2) 仅当 isalpha() 为 false 时才打印 Word。 这里只是意味着最后一个词,"HEART" 不会被打印出来。

解决(1)可以通过添加if word==""来检查elif word[0].lower() > "g" :之前的word是否为空串。如果它是一个空字符串,我们可以跳过迭代,解决问题 (1)。要跳过,您可以使用 continue 语句。What's continue? Detailed explanation here. 或者只是 word = ""

要解决 (2),您可以通过在引号 q+=" " {q=q+"" 的快捷方式后添加一个空格来做一个简单的技巧,从而确保非字母作为最后一个字符。输入 quote.Or 后立即执行您可以添加

if word[0].lower() > "g" :
    print (word.upper())

到最后。 现在,我建议的最终代码将是,

q = input ("Quote : ")
q+=" "
word = ""
for a in q :
    if a.isalpha() == True :
        word += a
    elif word =="":
        continue
    elif word[0].lower() > "g" :
        print (word.upper())
        word = ""
    else :
        word = ""