Question

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?

Was it helpful?

Solution

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'

OTHER TIPS

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top