Fundamentals 4 min read

How to Capitalize Sentences in Python: Simple Code Solutions

This article demonstrates how to transform a lowercase English sentence into a properly capitalized version in Python by splitting the text on punctuation marks and converting the first character of each segment to uppercase, offering two concise code solutions with sample input and output.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Capitalize Sentences in Python: Simple Code Solutions

1. Introduction

Earlier in a Python community a user asked how to convert a string such as "hello. my name is Joe. what is your name?" into a version where each sentence starts with an uppercase letter, e.g., "Hello. My name is Joe. What is your name?".

2. Implementation

One solution splits the text by periods, capitalizes the first character of each fragment, and joins them back with periods.

# coding:utf-8
# @Time : 2022/5/4 10:46
# @Author: PiPi
text = "hello.my name is Joe.what is your name?"
print(".".join([i[:1].upper() + i[1:] for i in text.split(".")]))

The code produces the expected capitalized output.

A second, more robust solution also handles exclamation marks and question marks.

s = 'i love Python.i love Python!i love Python,and do you love C++?'
st = s.replace('.', '.
').replace('!', '!
').replace('?', '?
')
result = ''.join(k[0].upper()+k[1:] for k in st.split('
')[:-1])
print(result)

This approach first inserts line breaks after each punctuation mark, then capitalizes the first character of each line, providing stronger handling of typical English sentence terminators.

3. Conclusion

The article presents two straightforward methods for capitalizing the first letter of each sentence in an English text using Python, encouraging readers to experiment with alternative solutions and share their own approaches.

Capitalization
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.