0

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.

2
  • Would you be able to supply a sample sentence input? This is solvable. I want to make sure it works on the input you choose Commented Oct 5, 2018 at 21:37
  • @Abhishek I edited my post to show a string I provided as input. Commented Oct 5, 2018 at 21:40

3 Answers 3

5

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.
Sign up to request clarification or add additional context in comments.

Comments

1

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.'

2 Comments

Thank you! That was the problem and I solved it by checking for the empty string and continue if empty.
@ChrisCharley check my elegant, concise solution for your problem. I edited the answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.