What is string.capwords() in Python?
Overview
The capwords() method of the String module in Python capitalizes all the words in a string. It does the following operations:
- It splits the given string using the split() method.
- It capitalizes every word using the capitalize() method.
- It joins the capitalized words into a single string using the join() method.
The method optionally accepts a parameter called sep.
- If a value is specified for the
sepparameter, the given separator splits and join the string (Steps 1 and 3). - If no value is specified for the
sepparameter, i.e., ifsepisNone, the leading and trailing whitespaces are deleted. A single space substitutes the runs of whitespace characters.
Syntax
string.capwords(s, sep=None)
Parameters
s: This is the given text/string.sep: This is the separator used to split and join the string.
Return value
The capwords() method returns a string where all the words are capitalized.
Code
import stringdef when_sep_is_none(text):new_str = string.capwords(text)print("When sep parameter is None")print("Original string - " + text)print("After applying capwords method - " + new_str)def when_sep_is_not_none(text, sep_val):new_str = string.capwords(text, sep=sep_val)print("When sep parameter is " + sep_val)print("Original string - " + text)print("After applying capwords method - " + new_str)if __name__ == "__main__":text = "hello educative, how are you?"when_sep_is_none(text)print("--" * 8)sep_val = "a"when_sep_is_not_none(text, sep_val)
Code explanation
- Line 1: We import the
stringmodule. - Lines 4 to 8: We define a method called
when_sep_is_none. This applies thecapwords()method on the given text with the value forsepasNone. - Lines 10 to 14: We define a method called
when_sep_is_not_none. This applies thecapwords()method on the given text with a non-none value forsep. - Lines 17 to 22: We define the main method where we define a text string and the value for
sep. We invoke the methodswhen_sep_is_noneandwhen_sep_is_not_nonewith the relevant arguments.
Note: When a non-none value is given for the
sepparameter, the words are determined based on thesepvalue.