22

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?

mrtsherman
  • 39,342
  • 23
  • 87
  • 111
NLPer
  • 511
  • 1
  • 4
  • 9

3 Answers3

47

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'
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
3

.capitalize() capitalises the first character ... which is a space :) Every other character gets lowercased.

Joe
  • 15,669
  • 4
  • 48
  • 83
2

It is because the first character is a space, not a letter.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445