String title() Method in Python

Python String title() Method

In Python, the title() method is a built-in string method used to convert the first character of each word in a string to uppercase and the rest of the characters to lowercase. It operates on a string and returns a new string with the modified format. The original string remains unchanged.

The title() method follows these rules:

  • The first character of each word is converted to uppercase.
  • Any following characters in the word are converted to lowercase.

Here's the basic syntax of the title() method:

string.title()

Example:

text = "hello world"
result = text.title()
print(result)

Output:

Hello World

As you can see, the first character of each word ("h" and "w") is converted to uppercase, while the other characters ("ello" and "orld") are converted to lowercase.

Keep in mind that the title() method does not modify the original string, but instead returns a new string with the desired title-case format. If you want to modify the original string in place, you can reassign the result back to the original variable:

text = "hello world"
text = text.title()
print(text)  # Output: Hello World

Also, note that the title() method treats characters following whitespace as the start of a new word. For example:

text = "python programming is fun!"
result = text.title()
print(result)

Output:

Python Programming Is Fun!

In this example, each word's first character after whitespace is converted to uppercase.