Capitalize a string

PythonString

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

@saua is right, and

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

will work for any string.

Solution 3 - Python

What about your_string.title()?

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

Solution 4 - Python

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

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

Solution 5 - Python

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().......

Solution 6 - Python

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.

Solution 7 - Python

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

In [1]: x = "hello"

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

Hope it helps.

Solution 8 - Python

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

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

> Gf12 23sadasd

Solution 9 - Python

str = str[:].upper()

this is the easiest way to do it in my opinion

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - Pythontigeronk2View Answer on Stackoverflow
Solution 2 - PythonBlair ConradView Answer on Stackoverflow
Solution 3 - PythonskylerView Answer on Stackoverflow
Solution 4 - PythonJoachim SauerView Answer on Stackoverflow
Solution 5 - PythonrbpView Answer on Stackoverflow
Solution 6 - PythonfaizView Answer on Stackoverflow
Solution 7 - PythonericView Answer on Stackoverflow
Solution 8 - PythonSaurabhView Answer on Stackoverflow
Solution 9 - PythonsaarView Answer on Stackoverflow