Python program to capitalize the first and last character of each word in a string
Last Updated :
27 Sep, 2023
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 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
def word_both_cap( str ):
return ' ' .join( map ( lambda s: s[: - 1 ] + s[ - 1 ].upper(),
s.title().split()))
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.
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
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)
Approach: 3: Using loop + title() + split() + upper() + strip() (Sclicing)
Python3
test_str = "hello world"
print ( "String before:" , test_str)
string = ""
for i in test_str.title().split():
string + = (i[: - 1 ] + i[ - 1 ].upper()) + ' '
print ( "String after:" , string.strip())
|
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.
Please Login to comment...