Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python capitalize() on a string starting with space

Tags:

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?

like image 429
NLPer Avatar asked Feb 11 '12 02:02

NLPer


People also ask

How do you capitalize the first letter after a space in Python?

capwords() capwords() is a python function that converts the first letter of every word into uppercase and every other letter into lowercase. The function takes the string as the parameter value and then returns the string with the first letter capital as the desired output.

What does capitalize () do in Python?

The capitalize() method returns a string where the first character is upper case, and the rest is lower case.

How do you capitalize certain letters in a string in Python?

The upper() method converts all lowercase characters in a string into uppercase characters and returns it.

How do you capitalize the first letter of a list in Python?

You can use str. capitalize() to capitalise each string. If you have any other uppercase letters in the string they will be lowered which may or may not be relevant.


1 Answers

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' 
like image 158
Gareth Latty Avatar answered Sep 19 '22 12:09

Gareth Latty