views:

351

answers:

2

Hi,

Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?

For example:

asimpletest -> Asimpletest
aSimpleTest -> ASimpleTest

I would like to be able to do all string lengths as well.

Thanks, Dan

+4  A: 
str = str[0].upper() + str[1:]

This should work with every string, except for the empty string ("").

Joachim Sauer
beat me to it, and yours is more elegant.
Unkwntech
+19  A: 

@saua is right, and

str = str[:1].upper() + str[1:]

will work for any string

Blair Conrad
Nice! Those are the kind of little tricks that I don't know ... I should use Python more often.
Joachim Sauer
'str' is a builtin name
hop
@hop: Yes it is. That doesn't make the code invalid, and since I was providing a refinement of saua's answer, I decided to keep the variable name, even though I would usually avoid it if I were writing code from scratch.
Blair Conrad