The capwords() method of the String module in Python capitalizes all the words in a string. It does the following operations:
The method optionally accepts a parameter called sep.
sep parameter, the given separator splits and join the string (Steps 1 and 3).sep parameter, i.e., if sep is None, the leading and trailing whitespaces are deleted. A single space substitutes the runs of whitespace characters.string.capwords(s, sep=None)
s: This is the given text/string.sep: This is the separator used to split and join the string.The capwords() method returns a string where all the words are capitalized.
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)
string module.when_sep_is_none. This applies the capwords() method on the given text with the value for sep as None.when_sep_is_not_none. This applies the capwords() method on the given text with a non-none value for sep.sep. We invoke the methods when_sep_is_none and when_sep_is_not_none with the relevant arguments.Note: When a non-none value is given for the
sepparameter, the words are determined based on thesepvalue.