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
: The string that you want to convert to title case.
Example:
In this example:
- The string
"hello, python world!"
becomes"Hello, Python World!"
, where each word starts with an uppercase letter.
Example with mixed case:
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:
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:
In this example, hyphens and commas are treated as word separators, so each word is capitalized individually.