Python str.title() function


str.title() Function in Python

The str.title() function in Python is used to convert the first letter of each word in a string to uppercase and all other characters in the word to lowercase. This is helpful for creating title-cased strings where each word starts with a capital letter.

Syntax:

string.title()
  • string: The string that you want to convert to title case.

Example:

# Example 1: Converting a string to title case my_string = "hello, python world!" title_string = my_string.title() print(title_string) # Output: "Hello, Python World!"

In this example:

  • The string "hello, python world!" becomes "Hello, Python World!", where each word starts with an uppercase letter.

Example with mixed case:

# Example 2: String with mixed case mixed_string = "PyTHon iS fuN!" title_mixed = mixed_string.title() print(title_mixed) # Output: "Python Is Fun!"

Here:

  • The string "PyTHon iS fuN!" is converted to "Python Is Fun!", where the first letter of each word is capitalized, and the remaining letters are in lowercase.

Example with numbers and special characters:

# Example 3: String with numbers and special characters special_string = "123abc python" title_special = special_string.title() print(title_special) # Output: "123Abc Python"

In this case:

  • The function capitalizes the first letter after any non-alphabetic characters like digits (123) or spaces. Therefore, "123abc" becomes "123Abc".

Key Points:

  • str.title() capitalizes the first character of each word and makes all other characters in the word lowercase.
  • Words are defined as sequences of alphabetic characters separated by non-alphabetic characters like spaces, punctuation, or numbers.
  • It does not modify the original string but returns a new string with the changes.
  • Non-alphabetic characters like numbers or punctuation do not affect the behavior, except for separating words.

Example with punctuation:

# Example 4: String with punctuation punct_string = "hello-world, python!" title_punct = punct_string.title() print(title_punct) # Output: "Hello-World, Python!"

In this example, hyphens and commas are treated as word separators, so each word is capitalized individually.