Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

s = 'the brown fox' 

...do something here...

s should be:

'The Brown Fox' 

What's the easiest way to do this?

like image 811
TIMEX Avatar asked Oct 11 '09 02:10

TIMEX


People also ask

How do you capitalize every word in a string?

We can capitalize each word of a string by the help of split() and substring() methods. By the help of split("\\s") method, we can get all words in an array. To get the first character, we can use substring() or charAt() method.

How do you capitalize first letter in text?

Or use Word's keyboard shortcut, Shift + F3 on Windows or fn + Shift + F3 for Mac, to change selected text between lowercase, UPPERCASE or capitalizing each word.

How do you capitalize the first letter of every word in a string C++?

string str = "something"; str[0] = toupper(str[0]); That's all you need to do.

Which function capitalize the first letter in each word of a text value?

At first, you need to split() the string on the basis of space and extract the first character using charAt(). Use toUpperCase() for the extracted character.


2 Answers

The .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" 
like image 177
Mark Rushakoff Avatar answered Sep 23 '22 21:09

Mark Rushakoff


The .title() method can't work well,

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

Try string.capwords() method,

import string string.capwords("they're bill's friends from the UK") >>>"They're Bill's Friends From The Uk" 

From the Python documentation on capwords:

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

like image 45
Chen Houwu Avatar answered Sep 23 '22 21:09

Chen Houwu