python capitalize() on a string starting with space

NLPer picture NLPer · Feb 11, 2012 · Viewed 33k times · Source

I was using the capitalize method on some strings in Python and one of strings starts with a space:

phrase = ' Lexical Semantics'

phrase.capitalize() returns ' lexical semantics' all in lower case. Why is that?

Answer

Gareth Latty picture Gareth Latty · Feb 11, 2012

This is the listed behaviour:

Return a copy of the string with its first character capitalized and the rest lowercased.

The first character is a space, the space is unchanged, the rest lowercased.

If you want to make it all uppercase, see str.upper(), or str.title() for the first letter of every word.

>>> phrase = 'lexical semantics'
>>> phrase.capitalize()
'Lexical semantics'
>>> phrase.upper()
'LEXICAL SEMANTICS'
>>> phrase.title()
'Lexical Semantics'

Or, if it's just a problem with the space:

>>> phrase = ' lexical semantics'
>>> phrase.strip().capitalize()
'Lexical semantics'