Chris Charley
Chris Charley

Reputation: 6573

IndexError: string index out of range using python 3.7

I checked similar posts but couldn't find any that solved my problem. The for loop that is commented out in my code produces correct output telling me that the indices I expect for a given sentence are correct.

The program asks for a couple of sentences and then capitalizes the first letter of the first word in the sentence.

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()

The traceback output is:

Enter a few sentences (with periods to end them) howdy. how are you. Traceback (most recent call last): File "C:/Old_Data/python/book/ch08/ch08_ex08_sentence_capitalizer.py", line 29, in main() File "C:/Old_Data/python/book/ch08/ch08_ex08_sentence_capitalizer.py", line 4, in main s = capitalize_sentence(sentence) File "C:/Old_Data/python/book/ch08/ch08_ex08_sentence_capitalizer.py", line 17, in capitalize_sentence if sentence[0] == ' ': # assuming 1 space separates sentences IndexError: string index out of range

Thanks for any help you can provide.

EDIT: the string I provided was: howdy. how are you.

Upvotes: 0

Views: 3982

Answers (3)

Acccumulation
Acccumulation

Reputation: 3591

Two options for fixing your function:

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

Upvotes: 1

nosklo
nosklo

Reputation: 222852

You have a input string where splitting leaves you with a sentence that has zero chars.

That makes your sentence[0] fail because sentence is the empty string "". You can't get the first char of a empty string. You get IndexError: string index out of range.

The for loop you commented works, because when the string is empty, it will never enter the inner code block. It will just be skipped printing nothing.

That's how I would write the function:

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

Testing it:

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

Upvotes: 1

Aleph Aleph
Aleph Aleph

Reputation: 5395

You are getting empty strings as a result of your split:

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

You are getting an exception when you are trying to get the [0]th character of an empty string. In your loop, you should check if the sentence is not empty and skip it (for example, using continue) if it is:

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

Upvotes: 5

Related Questions