Capitalize first letter ONLY of a string in Python
23,031
Solution 1
Like Barmar said, you can just capitalize the first character and concatenate it with the remainder of the string.
myString = 'tHatTimeIAteMyPANTS'
newString = "%s%s" % (myString[0].upper(), myString[1:])
print(newString) # THatTimeIAteMyPANTS
Solution 2
Like this:
myString= myString[:1].upper() + myString[1:]
print myString

Author by
Oliver Vakomies
Updated on July 05, 2022Comments
-
Oliver Vakomies over 1 year
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'