Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize a string

Tags:

python

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.

like image 282
Dan Avatar asked Dec 09 '08 11:12

Dan


People also ask

How do you capitalize characters in a string?

To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.

How do you capitalize strings in python?

Python String capitalize() The capitalize() method converts the first character of a string to an uppercase letter and all other alphabets to lowercase.

Should strings be capitalized?

The String type is capitalized because it is a class, like Object , not a primitive type like boolean or int (the other types you probably ran across).

What does capitalization of a string do?

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


8 Answers

>>> b = "my name"
>>> b.capitalize()
'My name'
>>> b.title()
'My Name'
like image 166
tigeronk2 Avatar answered Oct 01 '22 02:10

tigeronk2


@saua is right, and

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

will work for any string.

like image 37
Blair Conrad Avatar answered Oct 01 '22 04:10

Blair Conrad


What about your_string.title()?

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

like image 36
skyler Avatar answered Oct 01 '22 03:10

skyler


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

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

like image 23
Joachim Sauer Avatar answered Oct 01 '22 03:10

Joachim Sauer


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().......
like image 36
rbp Avatar answered Oct 01 '22 03:10

rbp


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.

like image 32
faiz Avatar answered Oct 01 '22 04:10

faiz


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

In [1]: x = "hello"

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

Hope it helps.

like image 21
eric Avatar answered Oct 01 '22 03:10

eric


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

like image 39
Saurabh Avatar answered Oct 01 '22 02:10

Saurabh