12

Possible Duplicate:
How to capitalize the first letter of each word in a string (Python)?

Is there an option to convert a string such that the first letter is uppercase and everythingelse is lower case....like below..i know there are upper and lower for converting to uppercase and lowercase....

string.upper() //for uppercase 
string.lower() //for lowercase
 string.lower() //for lowercase

INPUT:-italic,ITALIC

OUTPUT:-Italic

http://docs.python.org/2/library/stdtypes.html

Community
  • 1
  • 1
user1795998
  • 4,937
  • 7
  • 23
  • 23
  • 3
    string.title() http://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python – hyleaus Nov 29 '12 at 21:40
  • 1
    http://docs.python.org/2/library/stdtypes.html#str.title – kreativitea Nov 29 '12 at 21:40
  • 1
    The "duplicate question" asks about how to capitalise the first letter of *each word* in the string; this question asks about how to capitalise only the first letter of the string. – Zenadix Jan 04 '16 at 16:26

3 Answers3

36

Just use str.title():

In [73]: a, b = "italic","ITALIC"

In [74]: a.title(), b.title()
Out[74]: ('Italic', 'Italic')

help() on str.title():

S.title() -> string

Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 1
    This may or may not be correct depending on what you consider a "word". For example, `'some_words'.title()` results in `'Some_Words'`. If you consider a sequence of non-whitespace characters to be a "word", then @SuperFamousGuy has the right answer for you: `.capitalize()`. – Chris Johnson May 09 '17 at 12:59
16

Yeah, just use the capitalize() method.

eg:

x = "hello"
x.capitalize()
print x   #prints Hello

Title will actually capitalize every word as if it were a title. Capitalize will only capitalize the first letter in a string.

SuperFamousGuy
  • 1,455
  • 11
  • 16
1

A simple way to do it:

my_string = 'italic'
newstr = my_string[0]
newstr = newstr.upper()
my_string = newstr + my_string[1:]

To make them lowercase (except the first letter):

my_string= 'ITALIC'
newstr = my_string[1:]
newstr = newstr.lower()
my_string = my_string[0] + newstr

I don't know if there is a built in to do this, but this should work.

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94