.isalpha和elif如何工作? (蟒蛇)

时间:2018-11-19 15:42:58

标签: python edx

我想创建一个代码,将一个句子中的大写单词(在“ 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一起存在

我需要知道如何解决它以及在哪里犯错

2 个答案:

答案 0 :(得分:0)

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

简单地说,您可以通过在尝试获取word之前检查word[0]是否为空来避免这种情况。

elif word and word[0].lower() > "g":

那至少应该避免例外。


  

但是我仍然遇到最后一个问题,尽管它以大于“ G”的字母开头,但它不会显示最后一个词

仅当您遇到非字母字符时才打印。因此,如果您通过一个单词然后没有打非字母字符,那么最后一个单词将不会被打印。

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

for a in q:
    ... etc.

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

答案 1 :(得分:0)

您将遇到两个问题

1)在word[0]为空字符串的情况下访问它。       如果您有连续的非字母会出现错误。  2)仅在isalpha()为假时才打印Word。       在这里,这仅表示最后一个单词“ HEART”将不会被打印。

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

要解决(2),您可以做一个简单的技巧,在引号q+=" " {q=q+""的快捷方式之后添加一个空格,从而确保最后一个字符不是字母。输入报价后立即执行。也可以添加

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 = ""
相关问题