Home » 2 ways To Capitalize the First Letter of Each Word of a String in Python

2 ways To Capitalize the First Letter of Each Word of a String in Python

Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
1 Year Subscription
Spring Framework Basics Video Course

In this article, we show you how to capitalize the first letter of each word of a string in python.

We will show you 2 examples of how to do this

Table of Contents

Example 1

In this example we are using the title() method

# How To Capitalize First Letter of Each Word of a String in Python
# Using the title() method of Python

string1='This is my sample text message'
print(string1.title())

string2='THIS IS MY SAMPLE TEXT MESSAGE'
print(string2.title())

string3='This IS my sAMple TEXt mEsSage'
print(string3.title())

You will see the following

>>> %Run stringcap1.py
This Is My Sample Text Message
This Is My Sample Text Message
This Is My Sample Text Message

Example 2

In this example we are using the capwords() method

# How To Capitalize First Letter of Each Word of a String in Python
# using the capswords() Method
import string

string1='This is my sample text message'
print(string.capwords(string1))

string2='THIS IS MY SAMPLE TEXT MESSAGE'
print(string.capwords(string2))

string3='This IS my sAMple TEXt mEsSage'
print(string.capwords(string3))

You will see the following

>>> %Run stringcap2.py
This Is My Sample Text Message
This Is My Sample Text Message
This Is My Sample Text Message

Link

This is in our github repository

https://github.com/programmershelp/maxpython/tree/main/code%20example/String%20examples

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More