Home > Article > Backend Development > How can I capitalize the first letter of each word in a string in Python?
Capitalizing the First Letter of Words in a String
Given a string like "the brown fox", how can we effortlessly capitalize the first letter of each word to obtain "The Brown Fox"?
Solution:
To capitalize the first letter of every word in a string, we utilize Python's ingenious .title() method. This method transforms strings into a format where each word's initial character is capitalized, regardless of whether the string contains ASCII or Unicode characters.
For instance:
>>> "hello world".title() 'Hello World' >>> u"hello world".title() u'Hello World'
It's worth noting that the .title() method's simplicity comes with a caveat. As highlighted in the official documentation, it treats apostrophes within contractions and possessives as word boundaries, occasionally leading to undesired results:
>>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk"
In such cases, customized string manipulation techniques or regular expressions may be necessary to achieve the desired capitalization behavior.
The above is the detailed content of How can I capitalize the first letter of each word in a string in Python?. For more information, please follow other related articles on the PHP Chinese website!