Open In App

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

Last Updated : 27 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




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

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




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



Similar Reads

Python Capitalize First Letter of Every Word in String
In text manipulation in Python, capitalizing the first letter of every word in a string is a common and essential task. This operation enhances the visual presentation of text and is particularly useful when dealing with user input, titles, or any scenario where proper capitalization is desired. In this article, we will explore some approaches to c
3 min read
Python program to capitalize the first letter of every word in the file
The following article contains programs to read a file and capitalize the first letter of every word in the file and print it as output. To capitalize the first letter we will use different methods using Python. The Python String Method is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the
3 min read
How to capitalize first character of string in Python
The problem of case changes in a string is quite common and has been discussed many times. Sometimes, we might have a problem like this in which we need to convert the initial character of the string to the upper case. Let’s discuss certain ways in which this can be performed. Method #1: Using string slicing + upper() This task can easily be perfor
5 min read
Pandas - Convert the first and last character of each word to upper case in a series
In python, if we wish to convert only the first character of every word to uppercase, we can use the capitalize() method. Or we can take just the first character of the string and change it to uppercase using the upper() method. So, to convert the first and last character of each word to upper case in a series we will be using a similar approach. F
2 min read
Capitalize Each String in a List of Strings in Python
In Python, manipulating strings is a common task, and capitalizing each string in a list is a straightforward yet essential operation. This article explores some simple and commonly used methods to achieve this goal. Each method has its advantages and use cases, providing flexibility for different scenarios. Capitalize Each String In A List Of Stri
3 min read
Python Program to swap the First and the Last Character of a string
Given a String. The task is to swap the first and the last character of the string. Examples: Input: GeeksForGeeks Output: seeksForGeekG Input: Python Output: nythoP Python string is immutable which means we cannot modify it directly. But Python has string slicing which makes it very easier to perform string operations and make modifications. Follo
2 min read
Capitalize first letter of a column in Pandas dataframe
Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to capitalize any specific column in given dataframe. Let's see how can we capitalize
2 min read
Python - Capitalize repeated characters in a string
Given an input string with lowercase letters, the task is to write a python program to identify the repeated characters in the string and capitalize them. Examples: Input: programming languageOutput: pRoGRAMMiNG lANGuAGeExplanation: r,m,n,a,g are repeated elements Input: geeks for geeksOutput: GEEKS for GEEKSExplanation: g,e,k,s are repeated elemen
4 min read
String capitalize() Method in Python
Python String capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter while making all other characters in the string lowercase letters. Example C/C++ Code # initializing a string name = "draco malfoy" #using capitalize function print(name.capitalize()) Outpu
2 min read
Python program to read file word by word
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word. Read file word by wordIn this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a bette
2 min read
three90RightbarBannerImg