【问题标题】:IndexError: string index out of range using python 3.7IndexError:使用python 3.7的字符串索引超出范围
【发布时间】:2018-10-05 21:32:31
【问题描述】:

我查看了类似的帖子,但找不到任何可以解决我问题的帖子。在我的代码中注释掉的 for 循环会产生正确的输出,告诉我我期望给定句子的索引是正确的。

程序要求输入几个句子,然后将句子中第一个单词的首字母大写。

def main():
    sentence = input('Enter a few sentences (with periods to end them) ')

    s = capitalize_sentence(sentence)

    #print(s)

def capitalize_sentence(s):
    sentences = s.split('.');
    result = ''

    for sentence in sentences:
        # these print as expected no index errors
        #for i in range(len(sentence)): 
        #    print(i, sentence[i])

        if sentence[0] == ' ': # assuming 1 space separates sentences
            result += ' '
            result += sentence[1].upper()
            result += sentence[2:]
            result += '.'
        else:
            result += sentence[0].upper()
            result += sentence[1:]
            result += '.'

    return result

main()

回溯输出为:

请输入几句话(用句号结尾)你好。你好吗。 Traceback(最近一次通话最后一次):文件 “C:/Old_Data/python/book/ch08/ch08_ex08_sentence_capitalizer.py”,行 29,在 main() 文件“C:/Old_Data/python/book/ch08/ch08_ex08_sentence_capitalizer.py”,行 4、主要 s = capitalize_sentence(sentence) 文件“C:/Old_Data/python/book/ch08/ch08_ex08_sentence_capitalizer.py”,行 17、大写句子 if sentence[0] == ' ': # 假设 1 个空格分隔句子 IndexError: string index out of range

感谢您提供的任何帮助。

编辑:我提供的字符串是:你好。你好吗。

【问题讨论】:

  • 你能提供一个样本sentence 输入吗?这是可以解决的。我想确保它适用于您选择的输入
  • @Abhishek 我编辑了我的帖子以显示我作为输入提供的字符串。

标签: python


【解决方案1】:

由于拆分,您得到了空字符串:

"howdy. how are you.".split('.')  # = ['howdy', ' how are you', '']

当您尝试获取空字符串的 [0]th 字符时,您会遇到异常。在你的循环中,你应该检查句子是否不为空,如果是则跳过它(例如,使用continue):

for sentence in sentences:
    if not sentence:
        continue
    elif sentence[0] == ' ': # assuming 1 space separates sentences
        result += ' '
        # etc.

【讨论】:

    【解决方案2】:

    您有一个输入字符串,其中拆分会留下一个字符为零的句子。

    这会使您的sentence[0] 失败,因为sentence 是空字符串""。您无法获取空字符串的第一个字符。你得到IndexError: string index out of range

    你评论的for循环有效,因为当字符串为空时,它永远不会进入内部代码块。它只会跳过不打印任何内容。

    这就是我编写函数的方式:

    def capitalize_sentence(s):
       return '. '.join(text.strip().capitalize() 
           for text in s.split('.') if text.strip()) + '.'
    

    测试它:

    >>> capitalize_sentence("howdy. how are you.")
    'Howdy. How are you.'
    

    【讨论】:

    • 谢谢!这就是问题所在,我通过检查空字符串来解决它,如果为空则继续。
    • @ChrisCharley 检查我为您的问题提供的优雅、简洁的解决方案。我编辑了答案。
    【解决方案3】:

    修复函数的两个选项:

    def capitalize_sentence(s):
        sentences = s.split('.');
        result = ''
        for sentence in sentences:
            for i, char in enumerate(sentence):
                if char == ' ':
                    result +=' '
                    continue
                result += char.upper()
                result += sentence[i+1:]
                result+='.'
                break
        return result
    
    def capitalize_sentence(s):
        sentences = s.split('.');
        result = ''
        for sentence in sentences:
            while sentence:
                result += sentence[0].upper()
                if sentence[0] != ' ':
                    result += sentence[1:]
                    result+='.'
                    break
                sentence = sentence[1:]
        return result
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多