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.
sentenceinput? This is solvable. I want to make sure it works on the input you choose