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:

  1. It splits the given string using the split() method.
  2. It capitalizes every word using the capitalize() method.
  3. 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 sep parameter, the given separator splits and join the string (Steps 1 and 3).
  • If no value is specified for the sep parameter, i.e., if sep is None, 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 string
def 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 string module.
  • Lines 4 to 8: We define a method called when_sep_is_none. This applies the capwords() method on the given text with the value for sep as None.
  • Lines 10 to 14: We define a method called when_sep_is_not_none. This applies the capwords() method on the given text with a non-none value for sep.
  • Lines 17 to 22: We define the main method where we define a text string and the value for 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 sep parameter, the words are determined based on the sep value.