![]() |
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 capitalize the initial letter of each word within a string, offering developers a range of options to suit their specific needs. Capitalize First Letter of Each Word in String using PythonBelow, are the ways of Python to Capitalize the First Letter Of Every Word In String.
Capitalize First Letter Of Every Word using capitalize() FunctionIn this example, the below code initializes a string, “capitalize the first letter,” and then uses the `capitalize()` method to convert the first letter of the entire string to uppercase. The print statements display both the original and capitalized strings. Python3
Output
Original String: capitalize first letter Capitalized String: Capitalize first letter Capitalize First Letter Of Every Word Using
|
original_string = "capitalize first letter" capitalized_string = original_string.title() print ( "Original String:" , original_string) print ( "Capitalized String:" , capitalized_string) |
Original String: capitalize first letter Capitalized String: Capitalize First Letter
capwords()
FunctionIn this example, below code imports the `capwords` function from the `string` module and applies it to capitalize the first letter of each word in the original string, “capitalize first letter.” The print statements then display both the original and capitalized strings.
from string import capwords original_string = "capitalize first letter" capitalized_string = capwords(original_string) print ( "Original String:" , original_string) print ( "Capitalized String:" , capitalized_string) |
Original String: capitalize first letter Capitalized String: Capitalize First Letter
In this example , below code initializes a string, “capitalize first letter,” and uses list comprehension to capitalize the first letter of each word. It then joins these capitalized words into a string. The print statements show both the original and capitalized strings.
original_string = "capitalize first letter" capitalized_string = ' ' .join([word.capitalize() for word in original_string.split()]) print ( "Original String:" , original_string) print ( "Capitalized String:" , capitalized_string) |
Original String: capitalize first letter Capitalized String: Capitalize First Letter
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |