How to Automatically Capitalize Sentences in Python Strings
This article explains how to transform a plain English string so that each sentence starts with a capital letter, covering the problem description, two Python implementations that handle periods, exclamation marks, and question marks, and shows the resulting outputs.
1. Introduction
Hello, I am PiPi. A follower asked how to process a string so that each sentence begins with a capital letter.
2. Problem Statement
Given an input string such as "hello. my name is Joe. what is your name?", the goal is to return a copy where the first character of each sentence is uppercase, e.g., "Hello. My name is Joe. What is your name?".
3. Implementation
First solution (splits by period and capitalizes the first character of each fragment):
# 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(".")]))Running the code produces the expected capitalized result.
Second solution (handles period, exclamation mark, and question mark for greater robustness):
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)The output correctly capitalizes each sentence regardless of the terminating punctuation.
4. Conclusion
The article presented two straightforward Python methods to capitalize the first letter of every sentence in an English text, covering common sentence terminators and providing ready-to-use code snippets.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
