首页 > 解决方案 > 标点符号导致错误

问题描述

您好,我有一小段代码,当使用测试短语运行时,当代码遇到标点符号时会出错。我认为 word 的值为 null,但我尝试将其转换为字符串以防止出现错误 IndexError。我已经逐步完成了该程序,并获得了 '' 而不是 ' ' 的值,并且想知道其中的区别,以便我可以解决此问题。该代码适用于所有字母。

word = ''
quote = input('enter a 1 sentence quote, non-alpha words: ').lower()
for character in quote:
    if character.isalpha() == True:
        word += character
    else:
        if str(word[0]) >= 'h':
            print(word.upper())
            word = ''

        else:
            word = ''

示例输入:无论你走到哪里,全心全意地去期望输出:所有大写的单词都在自己的行中。随心所欲

标签: python

解决方案


''是一个完全有效的字符串。您不需要“投射”它或任何类似的东西。

但它是一个字符串。所以它没有第一个字符word[0]。如果您阅读错误消息:

IndexError: string index out of range

......这就是它告诉你的。问题不在于您没有字符串,而在于您的字符串不够大,无法包含第一个字符。


您在这里要做的是在询问其第一个字符之前检查空字符串:

if word and word[0] >= 'h':
    print(word.upper())
    word = ''
else:
    word = ''

…或处理IndexError

try:
    if word[0] >= 'h':
        print(word.upper())
        word = ''
    else:
        word = ''
except IndexError:
    word = ''

通常,在 Python 中,只try做某事并处理错误(更容易询问宽恕比权限,而不是Look Before You Leap)更惯用,但在某些情况下,首先检查会更具可读性,我认为这是其中一种情况。


推荐阅读