Any difference between str.capitalize() and str.title()?

Question:

Is there any difference in str.title() vs str.capitalize()? My understanding from the docs is that both methods capitalize the first letter of a word and make the rest of the letters lowercase. Did anyone run into a situation where they cannot be used interchangeably?

Asked By: mysl

||

Answers:

Yep, there’s a difference. 2, actually.

  1. In str.title(), where words contain apostrophes, the letter after the apostrophe will be capitalised.
  2. str.title() capitalises every word of a sentence, whereas str.capitalize() capitalises just the first word of the entire string.

From the docs:

str.title()

Return a titlecased version of the string where words start with an
uppercase character and the remaining characters are lowercase.

For example:

>>> 'Hello world'.title()
'Hello World'

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:

Answered By: PeptideWitch

title() changes every word, but capitalize() only the first word in a sentence:

>>> a = 'nice question'
>>> a.title()
'Nice Question'
>>> a.capitalize()
'Nice question'
>>> 
Answered By: lenik

I will explain the difference with an example:

Suppose you have a string, str1 = 'a b 2w' and you want to capitalize all the first characters but if the first character is a digit then you do not want to change.
Desired output -> A B 2w

If you do str1.title() it will result in this -> A B 2W
and str1.capitalize() will give the following result -> A b 2w

To get the desired result, you have to do something like this:

for x in str1.split():

str1 = str1.replace(x, x.capitalize()) 
Answered By: Anshul Sharma