Friday, December 27, 2024
Google search engine
HomeLanguagesPython program to capitalize the first and last character of each word...

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

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 neveropen
Output: WelcomE TO GeeksforgeekS

Approach:1

  • Access the last element using indexing.
  • Capitalize the first word using the title() method.
  • Then join 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 neveropen"
print("String before:", s)
print("String after:", word_both_cap(str))


Output

String before: welcome to neveropen
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.

Time Complexity: O(n)

Auxiliary Space: O(n), where n is number of characters in string.

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 neveropen"
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 neveropen
String after: WelcomE TO GeeksforgeekS

Time Complexity: O(n)

Auxiliary Space: O(n)

Approach: 3: Using loop + title() + split() + upper() + strip() (Sclicing)

Python3




"""Python program to capitalize
the first character and the last character
of each word in the string"""
 
# Taking the strign input
test_str = "hello world"
 
# Without any changes in the string
print("String before:", test_str)
# Creating an empty string
string = ""
 
# Using for loop + the functions to capitalize
for i in test_str.title().split():
    string += (i[:-1] + i[-1].upper()) + ' '
     
print("String after:", string.strip())  # To remove the space at the end


Output

String before: hello world
String after: HellO WorlD

Time Complexity: O(n)

Auxiliary Space: O(n), where n is number of characters in string.

RELATED ARTICLES

Most Popular

Recent Comments