Capitalize the First and Last Letters of Each Word in Python String

Recently, I was working on a text-cleaning project where I had to format customer names for a U.S.-based retail dataset. The requirement was unusual; instead of simply capitalizing the first letter of each word, I needed to capitalize both the first and last letters of every word in the string.

At first, I thought Python’s built-in method title() would be enough. But soon I realized that title() only capitalizes the first letter and makes the rest lowercase. There was no direct function to handle both the first and last letters.

So, I explored different approaches and found a few simple ways to achieve this. In this tutorial, I’ll share these methods with you.

Method 1: Use title() Method and Slicing

The title() method is used to capitalize the first letter of each word in the string in Python.

Then, we can apply slicing in Python to capitalize each word’s last letter by connecting the second character to the last character of each word and concatenating it with the capitalized substring.

Code

text = "the quick brown fox jumps over the lazy dog"
capitalized_text = text.title()
capitalized_text = capitalized_text[:-1] + capitalized_text[-1].upper()
print(capitalized_text)

Output

The Quick Brown Fox Jumps Over The Lazy DoG

I executed the above example code and added the screenshot below.

program to capitalize first and last letter of string in python

This method combines Python’s title() and slicing to capitalize the first and last letters of each word in a string.

Method 2: Use the capitalize() Method and String Slicing in Python

The capitalize() method is used for capitalizing the first letter of a string in Python. By combining it with string slicing, we can extend its functionality to capitalize the last letter of each word.

Code

sentence = "the united States of America is a diverse country"
capitalized_sentence = ' '.join(word[:-1].capitalize() + word[-1].upper() for word in sentence.split())
print(capitalized_sentence)

Output

ThE UniteD StateS OF AmericA IS A DiversE CountrY

I executed the above example code and added the screenshot below.

capitalize first and last letter in python

This method uses capitalize() and slicing to make both the first and last letters of each word uppercase in a Python string.

Method 3: Use for loop in Python

A for loop provides flexibility in manipulating strings character by character. By combining it with slicing, we can efficiently capitalize the first and last letters of each word.

Code

sentence = "los angeles is known for its entertainment industry"
capitalized_sentence = ""
for word in sentence.split():
    capitalized_word = word[0].upper() + word[1:-1] + word[-1].upper()
    capitalized_sentence += capitalized_word + " "
print(capitalized_sentence)

Output

LoS AngeleS IS KnowN FoR ItS EntertainmenT IndustrY

I executed the above example code and added the screenshot below.

How to capitalize first and last letter of each word in python

We split the sentence into words and iterate over each word in Python. We capitalize the first letter using slicing and capitalize the last letter separately for each word. Then, we concatenate both parts to form the capitalized Python string.

Method 4: Use List Comprehension

List comprehension offers a concise and efficient way to manipulate lists in Python. By combining it with slicing, we can capitalize the first and last letters of each word in a string.

Here is an example:

Code

sentence = "san francisco is famous for its iconic landmarks"
capitalized_sentence = ' '.join(word[0].upper() + word[1:-1] + word[-1].upper() for word in sentence.split())
print(capitalized_sentence)

We split the sentence into words using split() in Python, then use list comprehension to iterate over each word.

Output

SaN FranciscO IS FamouS FoR ItS IconiC LandmarkS

I executed the above example code and added the screenshot below.

string capitalize first and last letter in Python

We capitalize the first letter using slicing and capitalize the last letter separately for each word. Then, we joined the capitalized words into a single string.

Method 5: Use Regular Expression

Regular expressions provide a powerful way to match and manipulate strings based on specific patterns. By defining a pattern to match the first and last letters of each word, we can capitalize them accordingly.

Code

import re

text = "the grand canyon is a must-visit destination"
capitalized_text = re.sub(r'\b(\w)(\w*)(\w)\b', lambda m: m.group(1).upper() + m.group(2) + m.group(3).upper(), text)
print(capitalized_text)

Output

ThE GranD CanyoN IS a MusT-VisiT DestinatioN

I executed the above example code and added the screenshot below.

capitalize first and last letter of each word in python

We use the re.sub() function to apply a custom lambda function to each match found by the regular expression pattern. The lambda function capitalizes both the first and last letters of each word.

Method 6: Use While Loop with Slicing

A while loop offers flexibility in controlling iterations based on specific conditions. By combining it with slicing, we can efficiently capitalize the first and last letters of each word in a string in Python.

Code:

sentence = "the golden gate bridge is an iconic landmark"
words = sentence.split()
index = 0
while index < len(words):
    words[index] = words[index][0].upper() + words[index][1:-1] + words[index][-1].upper()
    index += 1
capitalized_sentence = ' '.join(words)
print(capitalized_sentence)

Output:

ThE GoldeN GatE BridgE IS AN IconiC LandmarK

I executed the above example code and added the screenshot below.

ways to capitalize first and last character of string in python

We split the sentence into words and initialized an index variable. We iterate over each word using a while loop, capitalize the first and last letters using slicing, and update the word in the list.

Method 7: Use a Custom Function

We can create a custom function that allows us to define specialized capitalization to get the required result.

By encapsulating the capitalization logic within a function in Python, we can reuse it across different strings and scenarios.

Here is the instance:

Code

def capitalize_first_and_last_letters(sentence):
    capitalized_words = [word[0].upper() + word[1:-1] + word[-1].upper() for word in sentence.split()]
    return ' '.join(capitalized_words)

sentence = "the grand canyon is a natural wonder"
capitalized_sentence = capitalize_first_and_last_letters(sentence)
print(capitalized_sentence)

We define a custom function capitalize_first_and_last_letters() that takes a string as input.

Output

ThE GranD CanyoN IS AA NaturaL WondeR

I executed the above example code and added the screenshot below.

How do i capitalize first and last letter of each word string in python

Within the Python function, we split the string into words, capitalized the first and last letters of each word in a string in Python, and joined the capitalized words into a single string.

Understanding multiple different methods and ways to capitalize the first and last letters of each word in a string in Python, with different practical examples, can help to solve their problem easily.

As each method offers distinct advantages and flexibility, from built-in string methods like title() and capitalize() to advanced methods such as regular expressions, list comprehensions, and custom functions.

You may also like to read these articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.