Open In App

Python program to capitalize the first and last character of each word in a string

Last Updated : 31 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore how to capitalize the first and last character of each word in a string in Python. It involves processing each word to transform its first and last letters to uppercase, while making the other characters lowercase.

Using List Comprehension

list comprehension and string slicing capitalize the first and last letters of each word in a sentence. It handles both short and long words, then joins them back into a single string.

Example:

Python
s = "hello world"

# Split `s` into words
w = s.split()

# process each word in the list `w`
res = ' '.join([
  
    # If the word has more than 1 character
    i[0].upper() + i[1:-1] + i[-1].upper() 
    if len(i) > 1 else i.upper()  # If word has only 1 char, capitalize the whole word
    for i in w  # Iterate through each word in the list `w`
])
print(res)

Output
HellO WorlD

Using map()

map() function with lambda to capitalize the first and last letters of each word. It processes each word in the string and then joins them into a single result.

Example:

Python
s = "welcome to geeksforgeeks"
res = ' '.join(
    map(
        lambda word: word[0].upper() + word[1:-1] + word[-1].upper()  # Capitalize first and last character
        if len(word) > 1 else word.upper(),  # If word length is 1, capitalize the whole word
        s.split()  # Split `s`into words
    )
)
print(res)

Output
WelcomE TO GeeksforgeekS

Using re.sub()

re.sub() method uses regular expressions to match the first and last characters of each word, applying capitalization to them. It efficiently processes the string in O(n) time complexity, where n is the length of the string.

Example:

Python
import re
s = "hello world"
res= re.sub(r'\b(\w)(\w*)(\w)\b',
             lambda match: match.group(1).upper()  # Capitalize first character
            + match.group(2)                      # Keep the middle part as is
            + match.group(3).upper(),             # Capitalize last character
            s)                                     # Apply the substitution to the string
print(res)

Output
HellO WorlD


Next Article

Similar Reads