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

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?



Solution 1:[1]

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

>>> a = 'silly question'
>>> a.title()
'Silly Question'
>>> a.capitalize()
'Silly question'
>>> 

Solution 2:[2]

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:

Solution 3:[3]

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()) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mad Physicist
Solution 3 keikai