Python string capwords() method
Last Updated : 02 Jan, 2025
Improve
capwords() method in Python is a part of the string
module and is used to capitalize the first letter of every word in a given string while converting all other letters to lowercase. To use capwords()
, the string
module must be imported as it is not a built-in string method.
import string
s = "learn python with geeksforgeeks!"
formatted = string.capwords(s)
print(formatted)
Output
Learn Python With Geeksforgeeks!
Explanation:
- The
string.capwords()
method processes the string 's'
by splitting it into words, capitalizing the first letter of each word and joining them back together. - The method also converts any uppercase letters in the middle of a word to lowercase.
- Punctuation marks are not removed but remain part of the resulting string.
Table of Content
Syntax of capwords() Method
string.capwords(string, sep=None)
Parameters
- string:
- The input string to be processed.
- sep (optional):
- The delimiter used to separate words in the string. If omitted, any whitespace is treated as the separator.
Return Type
- Returns a new string where the first letter of each word is capitalized, and all other letters are converted to lowercase.
Examples of String capwords()
1. Capitalizing words in a simple sentence
When working with sentences, ensuring consistent capitalization can significantly enhance readability. This method is especially useful in titles and headings.
import string
s = "learn python with geeksforgeeks!"
formatted = string.capwords(s)
print(formatted)
Output
Learn Python With Geeksforgeeks!
Explanation:
- The input string '
s'
contains all lowercase words. - The
capwords()
method capitalizes the first letter of each word and lowers the rest, resulting in proper formatting.
2. Using a custom separator
When strings use specific separators like commas or hyphens instead of spaces, the sep
parameter can be used for precise formatting.
import string
s = "learn-python-with-geeksforgeeks!"
formatted = string.capwords(s, sep="-")
print(formatted)
Output
Learn-Python-With-Geeksforgeeks!
Explanation:
- The
sep
parameter specifies"-"
as the delimiter. - The method capitalizes the first letter of each segment separated by the hyphen and keeps the separator intact.
3. Handling mixed-case strings
This method is ideal for normalizing text where some words are already capitalized or contain uppercase letters.
import string
s = "lEARn pythON wITh gEEksfORgEEks!"
formatted = string.capwords(s)
print(formatted)
Output
Learn Python With Geeksforgeeks!
Explanation:
- The input string contains a mix of uppercase and lowercase letters.
- The
capwords()
method converts all letters to lowercase first, then capitalizes the first letter of each word.