Capitalize a string

Viewed 80441

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.

9 Answers

@saua is right, and

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

will work for any string.

s = s[0].upper() + s[1:]

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

You can use the str.capitalize() function to do that

In [1]: x = "hello"

In [2]: x.capitalize()
Out[2]: 'Hello'

Hope it helps.

Related