Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Difficulty Level : Medium
  • Last Updated : 30 Jan, 2020

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.




# 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))

Output:

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

Start Your Coding Journey Now!