Skip to content
Related Articles

Related Articles

Python program to capitalize the first and last character of each word in a string
  • Last Updated : 30 Jan, 2020
GeeksforGeeks - Summer Carnival Banner

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :