The string module in the Python's standard library provides a number of tools for manipulating strings. Among them is the capwords()
function which capitalizes each word in the input string.
capwords(s, sep = None)
s |
A required argument representing the string to capitalize. |
sep |
An optional argument used to indicate a delimiter for the input string. It defaults to a whitespace(" " ) |
The function returns a new string with all the words of the input string capitalized.
In order to use the function, we must first import the string module in our program.
Example with sep given
How the function works
The function splits the input string into words using the split()
method, capitalizes each word using the capitalize()
method, and finally joins the capitalized words using the join()
method.
If the optional second argument sep
is absent or None,
adjoining whitespace characters are replaced by a single space while leading and trailing whitespace are removed, otherwise sep
is used to split and join the words.