Home >Backend Development >Python Tutorial >How to Capitalize the First Letter of Each Word in a String?

How to Capitalize the First Letter of Each Word in a String?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 00:01:30672browse

How to Capitalize the First Letter of Each Word in a String?

Capitalizing Initial Characters in Strings: A Comprehensive Guide

Problem:
How to effortlessly capitalize the first letter of each word in a given string? Consider the example:

"s = 'the brown fox'"

After manipulating "s", the expected output is:
"The Brown Fox"

Solution:
The most straightforward approach to solving this problem lies in the utilization of the ".title()" method. This method operates on strings, both ASCII and Unicode, and performs the desired capitalization:

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

Caution:
Strings containing apostrophes should be handled carefully. As noted in the documentation, apostrophes in contractions and possessives may lead to unexpected behavior due to the method's word boundary definition:

print("they're bill's friends from the UK".title())
# Output: They'Re Bill'S Friends From The Uk

The above is the detailed content of How to Capitalize the First Letter of Each Word in a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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