Dan
Dan

Reputation: 35433

Capitalize a string

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.

Upvotes: 63

Views: 84567

Answers (8)

Eric
Eric

Reputation: 2729

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

In [1]: x = "hello"

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

Hope it helps.

Upvotes: 0

Saurabh
Saurabh

Reputation: 7833

Docs can be found here for string functions https://docs.python.org/2.6/library/string.html#string-functions
Below code capitializes first letter with space as a separtor

s="gf12 23sadasd"
print( string.capwords(s, ' ') )

Gf12 23sadasd

Upvotes: 1

Blair Conrad
Blair Conrad

Reputation: 241714

@saua is right, and

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

will work for any string.

Upvotes: 80

Joachim Sauer
Joachim Sauer

Reputation: 308001

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

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

Upvotes: 8

faiz
faiz

Reputation: 123

for capitalize first word;

a="asimpletest"
print a.capitalize()

for make all the string uppercase use the following tip;

print a.upper()

this is the easy one i think.

Upvotes: 2

rbp
rbp

Reputation: 1898

this actually gives you a capitalized word, instead of just capitalizing the first letter

cApItAlIzE -> Capitalize

def capitalize(str): 
    return str[:1].upper() + str[1:].lower().......

Upvotes: 4

tigeronk2
tigeronk2

Reputation: 2650

>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'

Upvotes: 143

skyler
skyler

Reputation: 8338

What about your_string.title()?

e.g. "banana".title() -> Banana

Upvotes: 11

Related Questions