Capitalize first letter ONLY of a string in Python

Oliver Vakomies picture Oliver Vakomies · Nov 6, 2016 · Viewed 20.9k times · Source

I'm trying to write a single line statement that assigns the value of a string to a variable after having ONLY the first letter capitalized, and all other letters left unchanged.

Example, if the string being used were:

myString = 'tHatTimeIAteMyPANTS'

Then the statement should result in another variable such as myString2 equal to:

myString2 = 'THatTimeIAteMyPANTS'

Answer

Ukimiku picture Ukimiku · Nov 6, 2016

Like this:

myString= myString[:1].upper() + myString[1:]
print myString