Python, Capitalize First Letter Of All Sentences


How to capitalize the first letter of all the sentences or how to capitalize the first letter in a paragraph using Python.

Let’s take some sample text.

sample_text = "lorem ipsum dolor sit amet, consectetur adipiscing elit. aliquam ornare volutpat magna ut euismod. vivamus vitae placerat erat. nulla facilisi. praesent ante mi, sodales sagittis condimentum vel, elementum nec augue."

The logic: We split the paragraph based on . (dot) to get a sentence list. Then we iterate on the list and capitalize the first letter of each sentence. One you have the capitalize list, you join it again to create a paragraph

# Python 3.8
sample_text = "lorem ipsum dolor sit amet, consectetur adipiscing elit. aliquam ornare volutpat magna ut euismod. vivamus vitae placerat erat. nulla facilisi. praesent ante mi, sodales sagittis condimentum vel, elementum nec augue."

def capitalizeFirst(text):
    str = []
    for i in text.split('.'):
        str.append(i.lstrip().capitalize())
    return '. '.join(str)
    
print(capitalizeFirst(sample_text))

# Output
'''
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ornare volutpat magna ut euismod. Vivamus vitae place
rat erat. Nulla facilisi. Praesent ante mi, sodales sagittis condimentum vel, elementum nec augue.
'''

As seen in the above, we created a method called capitalizeFirst which takes the paragraph as input. Using split method we first separated the sentences using the dot as a separator. We have used lstrip to strip leading whitespace. capitalize method is used to capitalize the first letter in a sentence. Finally, we used join to convert the list to string.

The above code can also be converted to a Python one liner.

# Python 3.8

>>> sample_text = "lorem ipsum dolor sit amet, consectetur adipiscing elit. aliquam ornare volutpat magna ut euismod. vivamus vitae placerat erat. nulla facilisi. praesent ante mi, sodales sagittis condimentum vel, elementum nec augue."

>>> print('. '.join([i.lstrip().capitalize() for i in sample_text.split('.')]))

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ornare volutpat magna ut euismod. Vivamus vitae placerat erat. Nulla facilisi. Praesent ante mi, sodales sagittis condimentum vel, elementum nec augue.