Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize first letter ONLY of a string in Python [duplicate]

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'
like image 536
Oliver Vakomies Avatar asked Nov 06 '16 20:11

Oliver Vakomies


People also ask

How do you capitalize the first letter of a string in Python?

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.

How do you change only first letter in capitalize in Python?

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.

How do I make the first letter capital of a string?

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.


1 Answers

Like this:

myString= myString[:1].upper() + myString[1:]
print myString
like image 67
Ukimiku Avatar answered Sep 19 '22 18:09

Ukimiku