How to convert first letter of each word to uppercase in Python

In this Python tutorial, we will learn how to convert first letter of each word to uppercase in a string in Python. To make it simple just look at this below example,

Hi, this is codespeedy and it provides coding solution

Now we have to write a Python code that will convert the first letter of each word to uppercase.
The output should be like this:

Hi, This Is Codespeedy And It Provides Coding Solution

You can see that now the string has become capitalized for each word in this string.

Convert first letter of each word capital in Python

In order to do capitalization in a string for each word, you can use an in-built method .title().

Take an example of a string first,

some_text = "Hey there how are you?"

Now let’s see how does this method work.

Python code to convert first letter of each word in uppercase in a string

some_text = "Hey there how are you?"
print(some_text.title())

Output:

$ python codespeedy.py
Hey There How Are You?

This is pretty easy, right?

Now take another example,

This time the string contains single quotes

some_text = "Hey I'm from CodeSpeedy. You're doing well right?"

Python code to convert first letter of each word to uppercase in a string that contains quotes

some_text = "Hey I'm from CodeSpeedy. You're doing well right?"
print(some_text.title())

Output:

$ python codespeedy.py
Hey I'M From Codespeedy. You'Re Doing Well Right?

Here you can see that every next to the quote letter are capitalized.

So in order to prevent this problem, we can use strings module.

import string
print(string.capwords("Hey I'm from CodeSpeedy. You're doing well right?"))

Output:

$ python codespeedy.py
Hey I'm From Codespeedy. You're Doing Well Right?

You may also learn,

Now you can see the uppercase conversion is successfully done.

So in this way, we can convert the first letter of each word to uppercase in a string in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *