snippetpythonCritical
How can I capitalize the first letter of each word in a string?
Viewed 0 times
howcapitalizeeachwordthelettercanfirststring
Problem
What’s the simplest way to transform this?
s = 'the brown fox's should be:'The Brown Fox'Solution
The
However, look out for strings with embedded apostrophes, as noted in the docs.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
.title() method of a string (either ASCII or Unicode is fine) does this:>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'However, look out for strings with embedded apostrophes, as noted in the docs.
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"Code Snippets
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"Context
Stack Overflow Q#1549641, score: 1426
Revisions (0)
No revisions yet.