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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

@saua is right, and

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

will work for any string.

Method 3

What about your_string.title()?

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

Method 4

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

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

Method 5

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

Method 6

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.

Method 7

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

In [1]: x = "hello"

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

Hope it helps.

Method 8

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

Method 9

str = str[:].upper()

this is the easiest way to do it in my opinion


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x