Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 03 Nov, 2022
Improve Article
Save Article

Given the string, the task is to capitalize 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:1

  • 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. 

Python3




# Python program to capitalize
# first and last character of
# each word of a String
 
 
# Function to do the same
def word_both_cap(str):
 
    # lambda 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

->There used a built-in function map( ) in place of that also we can use filter( ).Basically these are the functions which take a list or any other function and give result on it.

Approach: 2: Using slicing and upper(),split() methods

Python3




# Python program to capitalize
# first and last character of
# each word of a String
 
s = "welcome to geeksforgeeks"
print("String before:", s)
a = s.split()
res = []
for i in a:
    x = i[0].upper()+i[1:-1]+i[-1].upper()
    res.append(x)
res = " ".join(res)
print("String after:", res)

Output

String before: welcome to geeksforgeeks
String after: WelcomE TO GeeksforgeekS

Time Complexity: O(n)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!