How to capitalize a string in Python

To capitalize a string in Python you can use the following snippet.

Sample Python

myPhrase = "HEllo wOrld!";
myPhrase = myPhrase.lower();
capChars = []
for word in myPhrase.split(' '):
  if len(word) > 1:
    capChars.append(word[0].upper() + word[1:])
  else:
      capChars.append(word.upper())
capChars = ' '.join(capChars)
print capChars;

Output:

Hello World!

another much simpler approach posted by Gomokoo on Twitter would be

print "HEllo wOrld!".lower().title();

Output:

Hello World!

Please Share us:
Please rate this snippet

2 thoughts on “How to capitalize a string in Python

Leave a Reply