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'
The first letter of a string can be capitalized using the capitalize() function. This method returns a string with the first letter capitalized. If you are looking to capitalize the first letter of the entire string the title() function should be used.
string capitalize() in Python Python String capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter, while making all other characters in the string lowercase letters.
To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.
Like this:
myString= myString[:1].upper() + myString[1:]
print myString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With