Kblo55 Kblo55 - 17 days ago 5
Python Question

Capitalizing the first letter of each sentence in Python

Here is my code:

def fix_capitalization(usrStr):
newString = ''
wordList = []
numLetters = 0
for s in usrStr.split('. '):
if s[0].isupper():
s = s.capitalize()
s = s.replace(' i ', " I ")
wordList.append(s)
if s.islower():
s = s.capitalize()
s = s.replace(' i ', " I ")
wordList.append(s)
numLetters += 1

if s[0].islower():
s = s.capitalize()
s = s.replace(' i ', " I ")
wordList.append(s)
numLetters += 1



newString = '. '.join(wordList)
return newString, numLetters


The string being passed in is:

i want some water. he has some. maybe he can give me some. i think I will ask.


Note that there are 4 spaces before
maybe
. The result that I want is:

I want some water. He has some. Maybe he can give me some. I think I will ask.


but I get:

I want some water. He has some. maybe he can give me some. I think I will ask.


I know that
maybe
isn't being capitalized because I split on
.
and that sentence has more than one space after the period, but I'm not sure how I can fix this or if there's a better way to go about what I'm doing. Any help would be greatly appreciated.

Answer

In for loop: First find the index of non-space character. Then replace s[0] with s[index].

Comments