Home > Backend Development > Python Tutorial > How can I capitalize the first letter of each word in a string in Python?

How can I capitalize the first letter of each word in a string in Python?

Susan Sarandon
Release: 2024-11-04 16:37:02
Original
254 people have browsed it

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'
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template