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

Given the string, the task is to capitalise the first and last character of each word in a string.

Examples:

Input: hello world 
Output: HellO WorlD

Input: welcome to geeksforgeeks
Output: WelcomE TO GeeksforgeekS

Approach:

  • Access the last element using indexing.
  • Capitalize the first word using title() method.
  • Then join the each word using join() method.
  • Perform all the operations inside lambda for writing the code in one-line.

Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to capitalize
# first and last character of 
# each word of a String
  
  
# Function to do the same
def word_both_cap(str):
      
    #lamda function for capitalizing the
    # first and last letter of words in 
    # the string
    return ' '.join(map(lambda s: s[:-1]+s[-1].upper(), 
                        s.title().split()))
      
      
# Driver's code
s = "welcome to geeksforgeeks"
print("String before:", s)
print("String after:", word_both_cap(str))

chevron_right


Output:

String before: welcome to geeksforgeeks
String after: WelcomE TO GeeksforgeekS
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.